Merge pull request #818 from gotify/upgrade-ui

Upgrade UI
This commit is contained in:
Jannis Mattheis 2025-08-08 10:58:23 +02:00 committed by GitHub
commit ebf6a6423d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
65 changed files with 5168 additions and 14162 deletions

View File

@ -7,12 +7,11 @@ ifdef GOTOOLCHAIN
else
GO_VERSION=$(shell go mod edit -json | jq -r .Toolchain | sed -e 's/go//')
endif
DOCKER_BUILD_IMAGE=gotify/build
DOCKER_BUILD_IMAGE=docker.io/gotify/build
DOCKER_WORKDIR=/proj
DOCKER_RUN=docker run --rm -e LD_FLAGS="$$LD_FLAGS" -v "$$PWD/.:${DOCKER_WORKDIR}" -v "`go env GOPATH`/pkg/mod/.:/go/pkg/mod:ro" -w ${DOCKER_WORKDIR}
DOCKER_GO_BUILD=go build -mod=readonly -a -installsuffix cgo -ldflags "$$LD_FLAGS"
DOCKER_TEST_LEVEL ?= 0 # Optionally run a test during docker build
NODE_OPTIONS=$(shell if node --help | grep -q -- "--openssl-legacy-provider"; then echo --openssl-legacy-provider; fi)
test: test-coverage test-js
check: check-go check-swagger check-js
@ -116,7 +115,7 @@ _build_within_docker:
${DOCKER_GO_BUILD} -o ${OUTPUT}
build-js:
(cd ui && NODE_OPTIONS="${NODE_OPTIONS}" yarn build)
(cd ui && yarn build)
build-linux-amd64:
${DOCKER_RUN} ${DOCKER_BUILD_IMAGE}:$(GO_VERSION)-linux-amd64 make _build_within_docker OUTPUT=${BUILD_DIR}/gotify-linux-amd64

View File

@ -1,2 +0,0 @@
src/setupTests.ts
src/registerServiceWorker.ts

View File

@ -1,91 +0,0 @@
---
extends:
- eslint:recommended
- plugin:@typescript-eslint/eslint-recommended
- plugin:@typescript-eslint/recommended
- plugin:@typescript-eslint/recommended-requiring-type-checking
- plugin:react/recommended
- plugin:import/errors
- plugin:import/typescript
- plugin:jest/recommended
- prettier
env:
browser: true
es6: true
node: true
parser: "@typescript-eslint/parser"
parserOptions:
project: tsconfig.json
sourceType: module
plugins:
- "@typescript-eslint"
- react
- import
- unicorn
settings:
react:
version: detect
rules:
consistent-return: error
default-case: error
default-param-last: error
no-loop-func: off
arrow-body-style: [error, as-needed]
import/no-useless-path-segments: error
import/group-exports: off
import/extensions: [error, never]
import/no-duplicates: error
import/first: error
import/no-unused-modules: error
unicorn/no-abusive-eslint-disable: off
unicorn/no-array-instanceof: error
unicorn/no-unreadable-array-destructuring: error
unicorn/no-zero-fractions: error
react/jsx-key: error
react/jsx-pascal-case: error
react/destructuring-assignment: off
react/function-component-definition: off
react/no-array-index-key: error
react/no-deprecated: off
react/no-string-refs: error
react/no-this-in-sfc: error
react/no-typos: error
react/no-unknown-property: error
react/prefer-stateless-function: off
react/prop-types: off
jest/expect-expect: off
jest/no-jasmine-globals: off
"@typescript-eslint/require-await": off
"@typescript-eslint/restrict-template-expressions": off
"@typescript-eslint/array-type": [error, {default: array-simple}]
"@typescript-eslint/await-thenable": error
"@typescript-eslint/no-unused-vars": error
"@typescript-eslint/no-use-before-define": off
"@typescript-eslint/no-unsafe-call": off
"@typescript-eslint/consistent-type-assertions": [error, {assertionStyle: as}]
"@typescript-eslint/no-extra-non-null-assertion": error
"@typescript-eslint/no-inferrable-types": error
"@typescript-eslint/no-this-alias": error
"@typescript-eslint/no-throw-literal": error
"@typescript-eslint/no-non-null-assertion": off
"@typescript-eslint/prefer-nullish-coalescing": error
"@typescript-eslint/prefer-optional-chain": error
"@typescript-eslint/prefer-readonly": off
"@typescript-eslint/unbound-method": error
"@typescript-eslint/no-empty-function": off
"@typescript-eslint/explicit-module-boundary-types": off
"@typescript-eslint/ban-ts-comment": off
"@typescript-eslint/no-floating-promises": off
"@typescript-eslint/no-unsafe-member-access": off
"@typescript-eslint/no-unsafe-return": off
"@typescript-eslint/no-unsafe-assignment": off
"@typescript-eslint/restrict-plus-operands": off
"@typescript-eslint/no-misused-promises": off
"@typescript-eslint/no-explicit-any": error

6
ui/eslint.config.mjs Normal file
View File

@ -0,0 +1,6 @@
// @ts-check
import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';
export default tseslint.config(eslint.configs.recommended, tseslint.configs.recommended);

View File

@ -4,7 +4,7 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#3f51b5">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="manifest" href="manifest.json">
<title>Gotify</title>
<link rel="apple-touch-icon-precomposed" sizes="57x57" href="static/apple-touch-icon-57x57.png" />
@ -35,8 +35,7 @@
Gotify requires JavaScript.
</noscript>
<div id="root"></div>
<% if (process.env.NODE_ENV === 'production') { %>
<script>window.config = %CONFIG%;</script>
<% } %>
<script>window.config = %CONFIG%;</script>
<script type="module" src="/src/index.tsx"></script>
</body>
</html>

View File

@ -5,72 +5,59 @@
"homepage": ".",
"proxy": "http://localhost:80",
"dependencies": {
"@material-ui/core": "^4.11.4",
"@material-ui/icons": "^4.9.1",
"axios": "^0.21.1",
"codemirror": "^5.61.1",
"detect-browser": "^5.2.0",
"js-base64": "^3.6.1",
"mobx": "^5.15.6",
"mobx-react": "^6.3.0",
"mobx-utils": "^5.6.1",
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.1",
"@mui/icons-material": "^7.2.0",
"@mui/material": "^7.2.0",
"@uiw/codemirror-theme-material": "^4.24.2",
"@uiw/react-codemirror": "^4.24.2",
"@vitejs/plugin-react": "^4.7.0",
"axios": "^1.11.0",
"detect-browser": "^5.3.0",
"mobx": "^6.13.7",
"mobx-react": "^9.2.0",
"mobx-utils": "^6.1.1",
"notifyjs": "^3.0.0",
"prop-types": "^15.6.2",
"react": "^16.4.2",
"react-codemirror2": "^7.2.1",
"react-dom": "^16.4.2",
"react-infinite": "^0.13.0",
"react-markdown": "^6.0.2",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0",
"react-timeago": "^6.2.1",
"remark-gfm": "^1.0.0",
"remove-markdown": "^0.3.0",
"typeface-roboto": "1.1.13"
"notistack": "^3.0.2",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"react-markdown": "^10.1.0",
"react-router": "^7.7.1",
"react-router-dom": "^7.7.1",
"react-timeago": "^8.3.0",
"react-virtuoso": "^4.13.0",
"remark-gfm": "^4.0.1",
"remove-markdown": "^0.6.2",
"tss-react": "^4.9.19",
"typeface-roboto": "1.1.13",
"vite": "^7.0.6",
"vitest": "^3.2.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=node",
"eject": "react-scripts eject",
"start": "vite",
"prebuild": "tsc",
"build": "vite build",
"test": "vitest --disable-console-intercept --no-file-parallelism",
"lint": "eslint \"src/**/*.{ts,tsx}\"",
"format": "prettier \"src/**/*.{ts,tsx}\" --write",
"testformat": "prettier \"src/**/*.{ts,tsx}\" --list-different"
},
"devDependencies": {
"@types/codemirror": "5.60.0",
"@types/detect-browser": "^4.0.0",
"@types/get-port": "^4.0.0",
"@types/jest": "^26.0.23",
"@types/js-base64": "^3.3.1",
"@types/node": "^15.12.2",
"@types/notifyjs": "^3.0.2",
"@types/puppeteer": "^5.4.6",
"@types/react": "^16.9.49",
"@types/react-dom": "^16.9.8",
"@types/react-infinite": "0.0.35",
"@types/react-router-dom": "^5.1.7",
"@types/remove-markdown": "^0.3.0",
"@types/rimraf": "^3.0.0",
"@typescript-eslint/eslint-plugin": "^4.1.0",
"@typescript-eslint/parser": "^4.1.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-jest": "^24.0.0",
"eslint-plugin-prefer-arrow": "^1.2.2",
"eslint-plugin-react": "^7.20.6",
"eslint-plugin-unicorn": "^21.0.0",
"get-port": "^5.1.1",
"prettier": "^2.3.1",
"puppeteer": "^17.1.3",
"react-scripts": "^4.0.3",
"rimraf": "^3.0.2",
"@eslint/js": "^9.32.0",
"@types/notifyjs": "^3.0.5",
"@types/react": "^19.1.9",
"@types/react-dom": "^19.1.7",
"@types/react-router-dom": "^5.3.3",
"@types/remove-markdown": "^0.3.4",
"eslint": "^9.32.0",
"get-port": "^7.1.0",
"prettier": "^3.6.2",
"puppeteer": "^24.15.0",
"rimraf": "^6.0.1",
"tree-kill": "^1.2.0",
"typescript": "4.0.2",
"wait-on": "^5.3.0"
},
"eslintConfig": {
"extends": "react-app"
"typescript": "^5.9.2",
"typescript-eslint": "^8.38.0",
"wait-on": "^8.0.4"
},
"browserslist": {
"production": [

View File

@ -35,7 +35,6 @@ func Register(r *gin.Engine, version model.VersionInfo, register bool) {
ui.GET("/", serveFile("index.html", "text/html", replaceConfig))
ui.GET("/index.html", serveFile("index.html", "text/html", replaceConfig))
ui.GET("/manifest.json", serveFile("manifest.json", "application/json", noop))
ui.GET("/asset-manifest.json", serveFile("asset-manifest.json", "application/json", noop))
subBox, err := fs.Sub(box, "build")
if err != nil {

View File

@ -1,9 +1,8 @@
import axios, {AxiosError, AxiosResponse} from 'axios';
import * as config from './config';
import {Base64} from 'js-base64';
import {detect} from 'detect-browser';
import {SnackReporter} from './snack/SnackManager';
import {observable} from 'mobx';
import {observable, makeObservable} from 'mobx';
import {IClient, IUser} from './types';
const tokenKey = 'gotify-login-key';
@ -12,16 +11,21 @@ export class CurrentUser {
private tokenCache: string | null = null;
private reconnectTimeoutId: number | null = null;
private reconnectTime = 7500;
@observable
public loggedIn = false;
@observable
public refreshKey = 0;
public authenticating = true;
@observable
public user: IUser = {name: 'unknown', admin: false, id: -1};
@observable
public connectionErrorMessage: string | null = null;
public constructor(private readonly snack: SnackReporter) {}
public constructor(private readonly snack: SnackReporter) {
makeObservable(this, {
loggedIn: observable,
authenticating: observable,
user: observable,
connectionErrorMessage: observable,
refreshKey: observable,
});
}
public token = (): string => {
if (this.tokenCache !== null) {
@ -51,12 +55,13 @@ export class CurrentUser {
this.login(name, pass);
return true;
})
.catch((error: AxiosError) => {
.catch((error: AxiosError<{error?: string; errorDescription?: string}>) => {
if (!error || !error.response) {
this.snack('No network connection or server unavailable.');
return false;
}
const {data} = error.response;
this.snack(
`Register failed: ${data?.error ?? 'unknown'}: ${data?.errorDescription ?? ''}`
);
@ -74,8 +79,7 @@ export class CurrentUser {
url: config.get('url') + 'client',
method: 'POST',
data: {name},
// eslint-disable-next-line @typescript-eslint/naming-convention
headers: {Authorization: 'Basic ' + Base64.encode(username + ':' + password)},
headers: {Authorization: 'Basic ' + btoa(username + ':' + password)},
})
.then((resp: AxiosResponse<IClient>) => {
this.snack(`A client named '${name}' was created for your session.`);
@ -98,10 +102,8 @@ export class CurrentUser {
return Promise.reject();
}
return (
axios
return axios
.create()
// eslint-disable-next-line @typescript-eslint/naming-convention
.get(config.get('url') + 'current/user', {headers: {'X-Gotify-Key': this.token()}})
.then((passThrough) => {
this.user = passThrough.data;
@ -131,8 +133,7 @@ export class CurrentUser {
this.logout();
}
return Promise.reject(error);
})
);
});
};
public logout = async () => {

View File

@ -1,47 +1,35 @@
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import TextField from '@material-ui/core/TextField';
import Tooltip from '@material-ui/core/Tooltip';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
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 {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,11 +75,4 @@ export default class AddDialog extends Component<IProps, IState> {
</DialogActions>
</Dialog>
);
}
private handleChange(propertyName: string, event: React.ChangeEvent<HTMLInputElement>) {
const state = this.state;
state[propertyName] = event.target.value;
this.setState(state);
}
}
};

View File

@ -1,7 +1,7 @@
import {BaseStore} from '../common/BaseStore';
import axios from 'axios';
import * as config from '../config';
import {action} from 'mobx';
import {action, makeObservable} from 'mobx';
import {SnackReporter} from '../snack/SnackManager';
import {IApplication} from '../types';
@ -10,6 +10,12 @@ export class AppStore extends BaseStore<IApplication> {
public constructor(private readonly snack: SnackReporter) {
super();
makeObservable(this, {
uploadImage: action,
update: action,
create: action,
});
}
protected requestItems = (): Promise<IApplication[]> =>
@ -23,7 +29,6 @@ export class AppStore extends BaseStore<IApplication> {
return this.snack('Application deleted');
});
@action
public uploadImage = async (id: number, file: Blob): Promise<void> => {
const formData = new FormData();
formData.append('file', file);
@ -34,7 +39,6 @@ export class AppStore extends BaseStore<IApplication> {
this.snack('Application image updated');
};
@action
public update = async (
id: number,
name: string,
@ -50,7 +54,6 @@ export class AppStore extends BaseStore<IApplication> {
this.snack('Application updated');
};
@action
public create = async (
name: string,
description: string,

View File

@ -1,50 +1,59 @@
import Grid from '@material-ui/core/Grid';
import IconButton from '@material-ui/core/IconButton';
import Paper from '@material-ui/core/Paper';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Delete from '@material-ui/icons/Delete';
import Edit from '@material-ui/icons/Edit';
import CloudUpload from '@material-ui/icons/CloudUpload';
import React, {ChangeEvent, Component, SFC} from 'react';
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';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
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 CloudUpload from '@mui/icons-material/CloudUpload';
import Button from '@mui/material/Button';
import ConfirmDialog from '../common/ConfirmDialog';
import DefaultPage from '../common/DefaultPage';
import Button from '@material-ui/core/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 item 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,9 +161,10 @@ const Row: SFC<IRowProps> = observer(
fUpload,
image,
fEdit,
}) => (
}: IRowProps) => {
return (
<TableRow>
<TableCell padding="default">
<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}}>
@ -203,7 +192,7 @@ const Row: SFC<IRowProps> = observer(
</IconButton>
</TableCell>
</TableRow>
)
);
);
};
export default inject('appStore')(Applications);
export default Applications;

View File

@ -1,59 +1,44 @@
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import TextField from '@material-ui/core/TextField';
import Tooltip from '@material-ui/core/Tooltip';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
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 {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,11 +84,4 @@ export default class UpdateDialog extends Component<IProps, IState> {
</DialogActions>
</Dialog>
);
}
private handleChange(propertyName: string, event: React.ChangeEvent<HTMLInputElement>) {
const state = this.state;
state[propertyName] = event.target.value;
this.setState(state);
}
}
};

View File

@ -1,34 +1,28 @@
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import TextField from '@material-ui/core/TextField';
import Tooltip from '@material-ui/core/Tooltip';
import React, {Component} from 'react';
import React, {useState} from 'react';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogTitle from '@mui/material/DialogTitle';
import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip';
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: string, event: React.ChangeEvent<HTMLInputElement>) {
const state = this.state;
state[propertyName] = event.target.value;
this.setState(state);
}
}
export default AddClientDialog;

View File

@ -1,13 +1,19 @@
import {BaseStore} from '../common/BaseStore';
import axios from 'axios';
import * as config from '../config';
import {action} from 'mobx';
import {action, makeObservable} from 'mobx';
import {SnackReporter} from '../snack/SnackManager';
import {IClient} from '../types';
export class ClientStore extends BaseStore<IClient> {
public constructor(private readonly snack: SnackReporter) {
super();
makeObservable(this, {
update: action,
createNoNotifcation: action,
create: action,
});
}
protected requestItems = (): Promise<IClient[]> =>
@ -19,21 +25,18 @@ export class ClientStore extends BaseStore<IClient> {
.then(() => this.snack('Client deleted'));
}
@action
public update = async (id: number, name: string): Promise<void> => {
await axios.put(`${config.get('url')}client/${id}`, {name});
await this.refresh();
this.snack('Client updated');
};
@action
public createNoNotifcation = async (name: string): Promise<IClient> => {
const client = await axios.post(`${config.get('url')}client`, {name});
await this.refresh();
return client.data;
};
@action
public create = async (name: string): Promise<void> => {
await this.createNoNotifcation(name);
this.snack('Client added');

View File

@ -1,46 +1,34 @@
import Grid from '@material-ui/core/Grid';
import IconButton from '@material-ui/core/IconButton';
import Paper from '@material-ui/core/Paper';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Delete from '@material-ui/icons/Delete';
import Edit from '@material-ui/icons/Edit';
import React, {Component, SFC} from 'react';
import React, {useEffect, useState} from 'react';
import Grid from '@mui/material/Grid';
import IconButton from '@mui/material/IconButton';
import Paper from '@mui/material/Paper';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
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 Button from '@mui/material/Button';
import ConfirmDialog from '../common/ConfirmDialog';
import DefaultPage from '../common/DefaultPage';
import Button from '@material-ui/core/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 item 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>
@ -139,4 +126,4 @@ const Row: SFC<IRowProps> = ({name, value, lastUsed, fEdit, fDelete}) => (
</TableRow>
);
export default inject('clientStore')(Clients);
export default Clients;

View File

@ -1,47 +1,30 @@
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import TextField from '@material-ui/core/TextField';
import Tooltip from '@material-ui/core/Tooltip';
import React, {Component} from 'react';
import React, {useState} from 'react';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import TextField from '@mui/material/TextField';
import Tooltip from '@mui/material/Tooltip';
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: string, event: React.ChangeEvent<HTMLInputElement>) {
const state = {};
state[propertyName] = event.target.value;
this.setState(state);
}
}
export default UpdateClientDialog;

View File

@ -1,4 +1,4 @@
import {action, observable} from 'mobx';
import {action, observable, makeObservable} from 'mobx';
interface HasID {
id: number;
@ -12,25 +12,21 @@ export interface IClearable {
* Base implementation for handling items with ids.
*/
export abstract class BaseStore<T extends HasID> implements IClearable {
@observable
protected items: T[] = [];
protected abstract requestItems(): Promise<T[]>;
protected abstract requestDelete(id: number): Promise<void>;
@action
public remove = async (id: number): Promise<void> => {
await this.requestDelete(id);
await this.refresh();
};
@action
public refresh = async (): Promise<void> => {
this.items = await this.requestItems().then((items) => items || []);
};
@action
public refreshIfMissing = async (id: number): Promise<void> => {
if (this.getByIDOrUndefined(id) === undefined) {
await this.refresh();
@ -50,8 +46,18 @@ export abstract class BaseStore<T extends HasID> implements IClearable {
public getItems = (): T[] => this.items;
@action
public clear = (): void => {
this.items = [];
};
constructor() {
// eslint-disable-next-line
makeObservable<BaseStore<any>, 'items'>(this, {
items: observable,
remove: action,
refresh: action,
refreshIfMissing: action,
clear: action,
});
}
}

View File

@ -1,9 +1,9 @@
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import React from 'react';
interface IProps {

View File

@ -1,6 +1,6 @@
import React from 'react';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';
interface ConnectionErrorBannerProps {
height: number;

View File

@ -1,21 +1,24 @@
import Paper from '@material-ui/core/Paper';
import {withStyles, WithStyles} from '@material-ui/core/styles';
import Paper from '@mui/material/Paper';
import {makeStyles} from 'tss-react/mui';
import * as React from 'react';
const styles = () => ({
const useStyles = makeStyles()(() => ({
paper: {
padding: 16,
},
});
}));
interface IProps extends WithStyles<'paper'> {
interface IProps {
style?: React.CSSProperties;
}
const Container: React.FC<IProps> = ({classes, children, style}) => (
const Container: React.FC<React.PropsWithChildren<IProps>> = ({children, style}) => {
const {classes} = useStyles();
return (
<Paper elevation={6} className={classes.paper} style={style}>
{children}
</Paper>
);
);
};
export default withStyles(styles)(Container);
export default Container;

View File

@ -1,42 +1,22 @@
import IconButton from '@material-ui/core/IconButton';
import Typography from '@material-ui/core/Typography';
import Visibility from '@material-ui/icons/Visibility';
import Copy from '@material-ui/icons/FileCopyOutlined';
import VisibilityOff from '@material-ui/icons/VisibilityOff';
import React, {Component, CSSProperties} from 'react';
import {Stores, inject} from '../inject';
import IconButton from '@mui/material/IconButton';
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, {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">
<Copy />
</IconButton>
<IconButton onClick={this.toggleVisibility} className="toggle-visibility">
{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');
@ -45,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,5 +1,5 @@
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import React, {FC} from 'react';
interface IProps {
@ -8,10 +8,15 @@ interface IProps {
maxWidth?: number;
}
const DefaultPage: FC<IProps> = ({title, rightControl, maxWidth = 700, children}) => (
const DefaultPage: FC<React.PropsWithChildren<IProps>> = ({
title,
rightControl,
maxWidth = 700,
children,
}) => (
<main style={{margin: '0 auto', maxWidth}}>
<Grid container spacing={4}>
<Grid item xs={12} style={{display: 'flex', flexWrap: 'wrap'}}>
<Grid size={{xs: 12}} style={{display: 'flex', flexWrap: 'wrap'}}>
<Typography variant="h4" style={{flex: 1}}>
{title}
</Typography>

View File

@ -1,4 +1,4 @@
import {Typography} from '@material-ui/core';
import {Typography} from '@mui/material';
import React from 'react';
import TimeAgo from 'react-timeago';

View File

@ -1,12 +1,12 @@
import CircularProgress from '@material-ui/core/CircularProgress';
import Grid from '@material-ui/core/Grid';
import CircularProgress from '@mui/material/CircularProgress';
import Grid from '@mui/material/Grid';
import React from 'react';
import DefaultPage from './DefaultPage';
export default function LoadingSpinner() {
return (
<DefaultPage title="" maxWidth={250}>
<Grid item xs={12} style={{textAlign: 'center'}}>
<Grid size={{xs: 12}} style={{textAlign: 'center'}}>
<CircularProgress size={40} />
</Grid>
</DefaultPage>

View File

@ -3,5 +3,5 @@ import ReactMarkdown from 'react-markdown';
import gfm from 'remark-gfm';
export const Markdown = ({children}: {children: string}) => (
<ReactMarkdown plugins={[gfm]}>{children}</ReactMarkdown>
<ReactMarkdown remarkPlugins={[gfm]}>{children}</ReactMarkdown>
);

View File

@ -1,4 +1,4 @@
import {TextField, TextFieldProps} from '@material-ui/core';
import {TextField, TextFieldProps} from '@mui/material';
import React from 'react';
export interface NumberFieldProps {

View File

@ -1,30 +1,22 @@
import Fab from '@material-ui/core/Fab';
import KeyboardArrowUp from '@material-ui/icons/KeyboardArrowUp';
import React, {Component} from 'react';
import Fab from '@mui/material/Fab';
import KeyboardArrowUp from '@mui/icons-material/KeyboardArrowUp';
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 currentScrollPos = window.pageYOffset;
const opacity = Math.min(currentScrollPos / 500, 1);
const ScrollUpButton = () => {
const [state, setState] = React.useState({display: 'none', opacity: 0});
React.useEffect(() => {
const scrollHandler = () => {
const currentScrollPos = Math.max(window.pageYOffset - 1000, 0);
const opacity = Math.min(currentScrollPos / 1000, 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,31 +1,27 @@
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import TextField from '@material-ui/core/TextField';
import Tooltip from '@material-ui/core/Tooltip';
import React, {Component} from 'react';
import {observable} from 'mobx';
import React, {useState} from 'react';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
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 {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

@ -6,7 +6,6 @@ export interface IConfig {
version: IVersion;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
declare global {
interface Window {
config?: Partial<IConfig>;

View File

@ -1,5 +1,5 @@
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import {createRoot} from 'react-dom/client';
import 'typeface-roboto';
import {initAxios} from './apiAuth';
import * as config from './config';
@ -9,14 +9,12 @@ import {CurrentUser} from './CurrentUser';
import {AppStore} from './application/AppStore';
import {WebSocketStore} from './message/WebSocketStore';
import {SnackManager} from './snack/SnackManager';
import {InjectProvider, StoreMapping} from './inject';
import {UserStore} from './user/UserStore';
import {MessagesStore} from './message/MessagesStore';
import {ClientStore} from './client/ClientStore';
import {PluginStore} from './plugin/PluginStore';
import {registerReactions} from './reactions';
const devUrl = 'http://localhost:3000/';
import {StoreContext, StoreMapping} from './stores';
const {port, hostname, protocol, pathname} = window.location;
const slashes = protocol.concat('//');
@ -50,12 +48,7 @@ const initStores = (): StoreMapping => {
};
(function clientJS() {
if (process.env.NODE_ENV === 'production') {
config.set('url', prodUrl);
} else {
config.set('url', devUrl);
config.set('register', true);
}
const stores = initStores();
initAxios(stores.currentUser, stores.snackManager.snack);
@ -67,11 +60,10 @@ const initStores = (): StoreMapping => {
stores.wsStore.close();
};
ReactDOM.render(
<InjectProvider stores={stores}>
createRoot(document.getElementById('root')!).render(
<StoreContext.Provider value={stores}>
<Layout />
</InjectProvider>,
document.getElementById('root')
</StoreContext.Provider>
);
unregister();
})();

View File

@ -1,49 +1,49 @@
import AppBar from '@material-ui/core/AppBar';
import Button from '@material-ui/core/Button';
import IconButton from '@material-ui/core/IconButton';
import {createStyles, Theme, WithStyles, withStyles} from '@material-ui/core/styles';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import AccountCircle from '@material-ui/icons/AccountCircle';
import Chat from '@material-ui/icons/Chat';
import DevicesOther from '@material-ui/icons/DevicesOther';
import ExitToApp from '@material-ui/icons/ExitToApp';
import Highlight from '@material-ui/icons/Highlight';
import GitHubIcon from '@material-ui/icons/GitHub';
import MenuIcon from '@material-ui/icons/Menu';
import Apps from '@material-ui/icons/Apps';
import SupervisorAccount from '@material-ui/icons/SupervisorAccount';
import React, {Component, CSSProperties} from 'react';
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 {makeStyles} from 'tss-react/mui';
import Toolbar from '@mui/material/Toolbar';
import Typography from '@mui/material/Typography';
import AccountCircle from '@mui/icons-material/AccountCircle';
import Chat from '@mui/icons-material/Chat';
import DevicesOther from '@mui/icons-material/DevicesOther';
import ExitToApp from '@mui/icons-material/ExitToApp';
import Highlight from '@mui/icons-material/Highlight';
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, {CSSProperties} from 'react';
import {Link} from 'react-router-dom';
import {observer} from 'mobx-react';
import {Hidden, PropTypes, withWidth} from '@material-ui/core';
import {Breakpoint} from '@material-ui/core/styles/createBreakpoints';
import {useMediaQuery} from '@mui/material';
const styles = (theme: Theme) =>
createStyles({
const useStyles = makeStyles()((theme: Theme) => ({
appBar: {
zIndex: theme.zIndex.drawer + 1,
[theme.breakpoints.down('xs')]: {
[theme.breakpoints.down('sm')]: {
paddingBottom: 10,
},
},
toolbar: {
justifyContent: 'space-between',
[theme.breakpoints.down('xs')]: {
[theme.breakpoints.down('sm')]: {
flexWrap: 'wrap',
},
},
menuButtons: {
display: 'flex',
[theme.breakpoints.down('sm')]: {
[theme.breakpoints.down('md')]: {
flex: 1,
},
justifyContent: 'center',
[theme.breakpoints.down('xs')]: {
[theme.breakpoints.down('sm')]: {
flexBasis: '100%',
marginTop: 5,
order: 1,
height: 50,
justifyContent: 'space-between',
alignItems: 'center',
},
},
title: {
@ -60,11 +60,9 @@ const styles = (theme: Theme) =>
color: 'inherit',
textDecoration: 'none',
},
});
}));
type Styles = WithStyles<'link' | 'menuButtons' | 'toolbar' | 'titleName' | 'title' | 'appBar'>;
interface IProps extends Styles {
interface IProps {
loggedIn: boolean;
name: string;
admin: boolean;
@ -73,15 +71,10 @@ interface IProps extends Styles {
showSettings: VoidFunction;
logout: VoidFunction;
style: CSSProperties;
width: Breakpoint;
setNavOpen: (open: boolean) => void;
}
@observer
class Header extends Component<IProps> {
public render() {
const {
classes,
const Header = ({
version,
name,
loggedIn,
@ -90,13 +83,15 @@ class Header extends Component<IProps> {
logout,
style,
setNavOpen,
width,
} = this.props;
const position = width === 'xs' ? 'sticky' : 'fixed';
showSettings,
}: IProps) => {
const {classes} = useStyles();
return (
<AppBar position={position} style={style} className={classes.appBar}>
<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}>
@ -112,9 +107,17 @@ class Header extends Component<IProps> {
</Typography>
</a>
</div>
{loggedIn && this.renderButtons(name, admin, logout, width, setNavOpen)}
{loggedIn && (
<Buttons
admin={admin}
name={name}
logout={logout}
setNavOpen={setNavOpen}
showSettings={showSettings}
/>
)}
<div>
<IconButton onClick={toggleTheme} color="inherit">
<IconButton onClick={toggleTheme} color="inherit" size="large">
<Highlight />
</IconButton>
@ -123,7 +126,7 @@ class Header extends Component<IProps> {
className={classes.link}
target="_blank"
rel="noopener noreferrer">
<IconButton color="inherit">
<IconButton color="inherit" size="large">
<GitHubIcon />
</IconButton>
</a>
@ -131,62 +134,51 @@ 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,
width: Breakpoint,
setNavOpen: (open: boolean) => void
) {
const {classes, showSettings} = this.props;
return (
<div className={classes.menuButtons}>
<Hidden smUp implementation="css">
<ResponsiveButton
sx={{display: {sm: 'none', xs: 'block'}}}
icon={<MenuIcon />}
onClick={() => setNavOpen(true)}
label="menu"
width={width}
color="inherit"
/>
</Hidden>
{admin && (
<Link className={classes.link} to="/users" id="navigate-users">
<ResponsiveButton
icon={<SupervisorAccount />}
label="users"
width={width}
color="inherit"
/>
<ResponsiveButton icon={<SupervisorAccount />} label="users" color="inherit" />
</Link>
)}
<Link className={classes.link} to="/applications" id="navigate-apps">
<ResponsiveButton icon={<Chat />} label="apps" width={width} color="inherit" />
<ResponsiveButton icon={<Chat />} label="apps" color="inherit" />
</Link>
<Link className={classes.link} to="/clients" id="navigate-clients">
<ResponsiveButton
icon={<DevicesOther />}
label="clients"
width={width}
color="inherit"
/>
<ResponsiveButton icon={<DevicesOther />} label="clients" color="inherit" />
</Link>
<Link className={classes.link} to="/plugins" id="navigate-plugins">
<ResponsiveButton
icon={<Apps />}
label="plugins"
width={width}
color="inherit"
/>
<ResponsiveButton icon={<Apps />} label="plugins" color="inherit" />
</Link>
<ResponsiveButton
icon={<AccountCircle />}
label={name}
onClick={showSettings}
id="changepw"
width={width}
color="inherit"
/>
<ResponsiveButton
@ -194,24 +186,27 @@ class Header extends Component<IProps> {
label="Logout"
onClick={logout}
id="logout"
width={width}
color="inherit"
/>
</div>
);
}
}
};
const ResponsiveButton: React.FC<{
width: Breakpoint;
color: PropTypes.Color;
color: 'inherit';
sx?: ButtonProps['sx'];
label: string;
id?: string;
onClick?: () => void;
icon: React.ReactNode;
}> = ({width, icon, label, ...rest}) => {
if (width === 'xs' || width === 'sm') {
return <IconButton {...rest}>{icon}</IconButton>;
}> = ({icon, label, ...rest}) => {
const matches = useMediaQuery('(max-width:1000px)');
if (matches) {
return (
<IconButton {...rest} size="large">
{icon}
</IconButton>
);
}
return (
<Button startIcon={icon} {...rest}>
@ -220,4 +215,4 @@ const ResponsiveButton: React.FC<{
);
};
export default withWidth()(withStyles(styles, {withTheme: true})(Header));
export default Header;

View File

@ -1,49 +1,48 @@
import {createMuiTheme, MuiThemeProvider, Theme, WithStyles, withStyles} from '@material-ui/core';
import CssBaseline from '@material-ui/core/CssBaseline';
import {createTheme, ThemeProvider, StyledEngineProvider, Theme} from '@mui/material';
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';
import {HashRouter, Navigate, Route, Routes} from 'react-router-dom';
import Header from './Header';
import LoadingSpinner from '../common/LoadingSpinner';
import Navigation from './Navigation';
import ScrollUpButton from '../common/ScrollUpButton';
import SettingsDialog from '../common/SettingsDialog';
import SnackBarHandler from '../snack/SnackBarHandler';
import * as config from '../config';
import Applications from '../application/Applications';
import Clients from '../client/Clients';
import Plugins from '../plugin/Plugins';
import PluginDetailView from '../plugin/PluginDetailView';
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';
import {SnackbarProvider} from 'notistack';
import LoadingSpinner from '../common/LoadingSpinner';
const styles = (theme: Theme) => ({
const useStyles = makeStyles()((theme: Theme) => ({
content: {
margin: '0 auto',
marginTop: 64,
padding: theme.spacing(4),
width: '100%',
[theme.breakpoints.down('xs')]: {
[theme.breakpoints.down('sm')]: {
marginTop: 0,
},
},
});
}));
const localStorageThemeKey = 'gotify-theme';
type ThemeKey = 'dark' | 'light';
const themeMap: Record<ThemeKey, Theme> = {
light: createMuiTheme({
light: createTheme({
palette: {
type: 'light',
mode: 'light',
},
}),
dark: createMuiTheme({
dark: createTheme({
palette: {
type: 'dark',
mode: 'dark',
},
}),
};
@ -51,50 +50,44 @@ const themeMap: Record<ThemeKey, Theme> = {
const isThemeKey = (value: string | null): value is ThemeKey =>
value === 'light' || value === 'dark';
@observer
class Layout extends React.Component<
WithStyles<'content'> & 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 {
classes,
currentUser: {
loggedIn,
authenticating,
user: {name, admin},
logout,
tryReconnect,
connectionErrorMessage,
refreshKey,
},
} = 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);
};
const authed = (children: React.ReactNode) => (
<RequireAuth loggedIn={loggedIn}>{children}</RequireAuth>
);
return (
<MuiThemeProvider theme={theme}>
<StyledEngineProvider injectFirst>
<ThemeProvider theme={theme}>
<HashRouter>
<div>
{/* This forces all components to fully rerender including useEffects.
The refreshKey is updated when store data was cleaned and pages should refetch their data. */}
<div key={refreshKey}>
{!connectionErrorMessage ? null : (
<ConnectionErrorBanner
height={64}
@ -105,65 +98,79 @@ class Layout extends React.Component<
<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>
{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} />
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/" element={authed(<Messages />)} />
<Route
path="/messages/:id"
element={authed(<Messages />)}
/>
<Route
exact
path="/applications"
component={Applications}
element={authed(<Applications />)}
/>
<Route exact path="/clients" component={Clients} />
<Route exact path="/users" component={Users} />
<Route exact path="/plugins" component={Plugins} />
<Route path="/clients" element={authed(<Clients />)} />
<Route path="/users" element={authed(<Users />)} />
<Route path="/plugins" element={authed(<Plugins />)} />
<Route
exact
path="/plugins/:id"
component={PluginDetailView}
element={authed(
<Lazy
component={() =>
import('../plugin/PluginDetailView')
}
/>
</Switch>
)}
/>
</Routes>
</main>
</div>
{showSettings && (
<SettingsDialog fClose={() => (this.showSettings = false)} />
<SettingsDialog fClose={() => setShowSettings(false)} />
)}
<ScrollUpButton />
<SnackBarHandler />
<SnackbarProvider />
</div>
</div>
</HashRouter>
</MuiThemeProvider>
</ThemeProvider>
</StyledEngineProvider>
);
}
});
private toggleTheme() {
this.currentTheme = this.currentTheme === 'dark' ? 'light' : 'dark';
localStorage.setItem(localStorageThemeKey, this.currentTheme);
}
}
// eslint-disable-next-line
const Lazy = ({component}: {component: () => Promise<{default: React.ComponentType<any>}>}) => {
const Component = React.lazy(component);
export default withStyles(styles, {withTheme: true})(inject('currentUser', 'snackManager')(Layout));
return (
<React.Suspense fallback={<LoadingSpinner />}>
<Component />
</React.Suspense>
);
};
const RequireAuth: React.FC<React.PropsWithChildren<{loggedIn: boolean}>> = ({
children,
loggedIn,
}) => {
return loggedIn ? <>{children}</> : <Navigate replace={true} to="/login" />;
};
export default Layout;

View File

@ -1,25 +1,25 @@
import Divider from '@material-ui/core/Divider';
import Drawer from '@material-ui/core/Drawer';
import {StyleRules, Theme, WithStyles, withStyles} from '@material-ui/core/styles';
import React, {Component} from 'react';
import Divider from '@mui/material/Divider';
import Drawer from '@mui/material/Drawer';
import {Theme} from '@mui/material/styles';
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,
Hidden,
IconButton,
Typography,
ListItem,
ListItemText,
ListItemAvatar,
Avatar,
} from '@material-ui/core';
import {DrawerProps} from '@material-ui/core/Drawer/Drawer';
import CloseIcon from '@material-ui/icons/Close';
ListItemButton,
} from '@mui/material';
import {DrawerProps} from '@mui/material/Drawer/Drawer';
import CloseIcon from '@mui/icons-material/Close';
import {makeStyles} from 'tss-react/mui';
import {useStores} from '../stores';
const styles = (theme: Theme): StyleRules<'root' | 'drawerPaper' | 'toolbar' | 'link'> => ({
const useStyles = makeStyles()((theme: Theme) => ({
root: {
height: '100%',
},
@ -29,14 +29,13 @@ const styles = (theme: Theme): StyleRules<'root' | 'drawerPaper' | 'toolbar' | '
minHeight: '100%',
height: '100vh',
},
toolbar: theme.mixins.toolbar,
// eslint-disable-next-line
toolbar: theme.mixins.toolbar as any,
link: {
color: 'inherit',
textDecoration: 'none',
},
});
type Styles = WithStyles<'root' | 'drawerPaper' | 'toolbar' | 'link'>;
}));
interface IProps {
loggedIn: boolean;
@ -44,16 +43,11 @@ interface IProps {
setNavOpen: (open: boolean) => void;
}
@observer
class Navigation extends Component<
IProps & Styles & Stores<'appStore'>,
{showRequestNotification: boolean}
> {
public state = {showRequestNotification: mayAllowPermission()};
public render() {
const {classes, loggedIn, appStore, navOpen, setNavOpen} = 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 =
@ -65,7 +59,7 @@ class Navigation extends Component<
className={`${classes.link} item`}
to={'/messages/' + app.id}
key={app.id}>
<ListItem button>
<ListItemButton>
<ListItemAvatar style={{minWidth: 42}}>
<Avatar
style={{width: 32, height: 32}}
@ -74,17 +68,17 @@ class Navigation extends Component<
/>
</ListItemAvatar>
<ListItemText primary={app.name} />
</ListItem>
</ListItemButton>
</Link>
));
const placeholderItems = [
<ListItem button disabled key={-1}>
<ListItemButton disabled key={-1}>
<ListItemText primary="Some Server" />
</ListItem>,
<ListItem button disabled key={-2}>
</ListItemButton>,
<ListItemButton disabled key={-2}>
<ListItemText primary="A Raspberry PI" />
</ListItem>,
</ListItemButton>,
];
return (
@ -95,9 +89,9 @@ class Navigation extends Component<
id="message-navigation">
<div className={classes.toolbar} />
<Link className={classes.link} to="/" onClick={() => setNavOpen(false)}>
<ListItem button disabled={!loggedIn} className="all">
<ListItemButton disabled={!loggedIn} className="all">
<ListItemText primary="All Messages" />
</ListItem>
</ListItemButton>
</Link>
<Divider />
<div>{loggedIn ? userApps : placeholderItems}</div>
@ -107,7 +101,7 @@ class Navigation extends Component<
<Button
onClick={() => {
requestPermission();
this.setState({showRequestNotification: false});
setShowRequestNotification(false);
}}>
Enable Notifications
</Button>
@ -115,27 +109,26 @@ class Navigation extends Component<
</Typography>
</ResponsiveDrawer>
);
}
}
});
const ResponsiveDrawer: React.FC<
DrawerProps & {navOpen: boolean; setNavOpen: (open: boolean) => void}
> = ({navOpen, setNavOpen, children, ...rest}) => (
<>
<Hidden smUp implementation="css">
<Drawer variant="temporary" open={navOpen} {...rest}>
<IconButton onClick={() => setNavOpen(false)}>
<Drawer
sx={{display: {sm: 'none', xs: 'block'}}}
variant="temporary"
open={navOpen}
{...rest}>
<IconButton onClick={() => setNavOpen(false)} size="large">
<CloseIcon />
</IconButton>
{children}
</Drawer>
</Hidden>
<Hidden xsDown implementation="css">
<Drawer variant="permanent" {...rest}>
<Drawer sx={{display: {xs: 'none', sm: 'block'}}} variant="permanent" {...rest}>
{children}
</Drawer>
</Hidden>
</>
);
export default withStyles(styles, {withTheme: true})(inject('appStore')(Navigation));
export default Navigation;

View File

@ -1,21 +1,21 @@
import {Button} from '@material-ui/core';
import IconButton from '@material-ui/core/IconButton';
import {createStyles, Theme, withStyles, WithStyles} from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import {ExpandLess, ExpandMore} from '@material-ui/icons';
import Delete from '@material-ui/icons/Delete';
import React, {RefObject} from 'react';
import {Button, Theme, useMediaQuery, useTheme} from '@mui/material';
import IconButton from '@mui/material/IconButton';
import {makeStyles} from 'tss-react/mui';
import Typography from '@mui/material/Typography';
import {ExpandLess, ExpandMore} from '@mui/icons-material';
import Delete from '@mui/icons-material/Delete';
import React from 'react';
import TimeAgo from 'react-timeago';
import Container from '../common/Container';
import {Markdown} from '../common/Markdown';
import * as config from '../config';
import {IMessageExtras} from '../types';
import {contentType, RenderMode} from './extras';
import {makeIntlFormatter} from 'react-timeago/defaultFormatter';
const PREVIEW_LENGTH = 500;
const styles = (theme: Theme) =>
createStyles({
const useStyles = makeStyles()((theme: Theme) => ({
header: {
display: 'flex',
flexWrap: 'wrap',
@ -29,21 +29,21 @@ const styles = (theme: Theme) =>
marginRight: -15,
},
wrapperPadding: {
padding: 12,
marginBottom: 12,
},
messageContentWrapper: {
minWidth: 200,
width: '100%',
maxWidth: 585,
},
image: {
marginRight: 15,
[theme.breakpoints.down('sm')]: {
[theme.breakpoints.down('md')]: {
width: 32,
height: 32,
},
},
date: {
[theme.breakpoints.down('sm')]: {
[theme.breakpoints.down('md')]: {
order: 1,
flexBasis: '100%',
opacity: 0.7,
@ -75,7 +75,7 @@ const styles = (theme: Theme) =>
maxWidth: '100%',
},
},
});
}));
interface IProps {
title: string;
@ -83,14 +83,11 @@ interface IProps {
date: string;
content: string;
priority: number;
appName: string;
fDelete: VoidFunction;
extras?: IMessageExtras;
height: (height: number) => void;
}
interface IState {
expanded: boolean;
isOverflowing: boolean;
onExpand: (expand: boolean) => void;
}
const priorityColor = (priority: number) => {
@ -103,53 +100,44 @@ const priorityColor = (priority: number) => {
}
};
class Message extends React.PureComponent<IProps & WithStyles<typeof styles>, IState> {
public state = {expanded: false, isOverflowing: false};
private node: HTMLDivElement | null = null;
private previewRef: RefObject<HTMLDivElement>;
const Message = ({
fDelete,
title,
date,
image,
priority,
content,
extras,
appName,
onExpand,
expanded: initialExpanded,
}: IProps) => {
const theme = useTheme();
const [previewRef, setPreviewRef] = React.useState<HTMLDivElement | null>(null);
const {classes} = useStyles();
const [expanded, setExpanded] = React.useState(initialExpanded);
const [isOverflowing, setOverflowing] = React.useState(false);
const dateWrapped = useMediaQuery(theme.breakpoints.down('md'));
constructor(props: IProps & WithStyles<typeof styles>) {
super(props);
this.previewRef = React.createRef();
}
React.useEffect(() => {
setOverflowing(!!previewRef && previewRef.scrollHeight > previewRef.clientHeight);
}, [previewRef]);
public componentDidMount = () => {
if (this.previewRef.current) {
this.setState({
isOverflowing:
this.previewRef.current.scrollHeight > this.previewRef.current.clientHeight,
});
}
this.updateHeightInParent();
};
React.useEffect(() => void onExpand(expanded), [expanded]);
public togglePreviewHeight = () => {
this.setState(
(state) => ({expanded: !state.expanded}),
() => this.updateHeightInParent()
);
};
const togglePreviewHeight = () => setExpanded((b) => !b);
private updateHeightInParent = () =>
this.props.height(this.node ? this.node.getBoundingClientRect().height : 0);
private renderContent = () => {
const content = this.props.content;
switch (contentType(this.props.extras)) {
const renderContent = () => {
switch (contentType(extras)) {
case RenderMode.Markdown:
return <Markdown>{content}</Markdown>;
case RenderMode.Plain:
default:
return <span className={this.props.classes.plainContent}>{content}</span>;
return <span className={classes.plainContent}>{content}</span>;
}
};
public render(): React.ReactNode {
const {fDelete, classes, title, date, image, priority} = this.props;
return (
<div className={`${classes.wrapperPadding} message`} ref={(ref) => (this.node = ref)}>
<div className={`${classes.wrapperPadding} message`}>
<Container
style={{
display: 'flex',
@ -158,11 +146,12 @@ class Message extends React.PureComponent<IProps & WithStyles<typeof styles>, IS
borderLeftWidth: 6,
borderLeftStyle: 'solid',
}}>
<div style={{display: 'flex', width: '100%'}}>
<div className={classes.imageWrapper}>
{image !== null ? (
<img
src={config.get('url') + image}
alt="app logo"
alt={`${appName} logo`}
width="70"
height="70"
className={classes.image}
@ -175,38 +164,46 @@ class Message extends React.PureComponent<IProps & WithStyles<typeof styles>, IS
{title}
</Typography>
<Typography variant="body1" className={classes.date}>
<TimeAgo date={date} />
<TimeAgo
date={date}
formatter={makeIntlFormatter({
style: dateWrapped ? 'long' : 'narrow',
})}
/>
</Typography>
<IconButton onClick={fDelete} className={`${classes.trash} delete`}>
<IconButton
onClick={fDelete}
className={`${classes.trash} delete`}
size="large">
<Delete />
</IconButton>
</div>
<Typography
component="div"
ref={this.previewRef}
ref={setPreviewRef}
className={`${classes.content} content ${
this.state.isOverflowing && this.state.expanded ? 'expanded' : ''
isOverflowing && expanded ? 'expanded' : ''
}`}>
{this.renderContent()}
{renderContent()}
</Typography>
</div>
{this.state.isOverflowing && (
</div>
{isOverflowing && (
<Button
style={{marginTop: 16}}
onClick={() => this.togglePreviewHeight()}
onClick={togglePreviewHeight}
variant="contained"
color="primary"
size="large"
fullWidth={true}
startIcon={this.state.expanded ? <ExpandLess /> : <ExpandMore />}>
{this.state.expanded ? 'Read Less' : 'Read More'}
startIcon={expanded ? <ExpandLess /> : <ExpandMore />}>
{expanded ? 'Read Less' : 'Read More'}
</Button>
)}
</Container>
</div>
);
}
}
};
export default withStyles(styles, {withTheme: true})(Message);
export default Message;

View File

@ -1,67 +1,93 @@
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
import React, {Component} from 'react';
import {RouteComponentProps} from 'react-router';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import React from 'react';
import {useParams} from 'react-router';
import DefaultPage from '../common/DefaultPage';
import Button from '@material-ui/core/Button';
import Button from '@mui/material/Button';
import Message from './Message';
import {observer} from 'mobx-react';
import {inject, Stores} from '../inject';
import {observable} from 'mobx';
import ReactInfinite from 'react-infinite';
import {IMessage} from '../types';
import ConfirmDialog from '../common/ConfirmDialog';
import LoadingSpinner from '../common/LoadingSpinner';
import {useStores} from '../stores';
import {Virtuoso} from 'react-virtuoso';
type IProps = RouteComponentProps<{id: string}>;
const Messages = observer(() => {
const {id} = useParams<{id: string}>();
const appId = id == null ? -1 : parseInt(id as string, 10);
interface IState {
appId: number;
}
@observer
class Messages extends Component<IProps & Stores<'messagesStore' | 'appStore'>, IState> {
@observable
private heights: Record<string, number> = {};
@observable
private deleteAll = false;
private static appId(props: IProps) {
if (props === undefined) {
return -1;
}
const {match} = props;
return match.params.id !== undefined ? parseInt(match.params.id, 10) : -1;
}
public state = {appId: -1};
private isLoadingMore = false;
public componentWillReceiveProps(nextProps: IProps & Stores<'messagesStore' | 'appStore'>) {
this.updateAllWithProps(nextProps);
}
public componentWillMount() {
window.onscroll = () => {
if (
window.innerHeight + window.pageYOffset >=
document.body.offsetHeight - window.innerHeight * 2
) {
this.checkIfLoadMore();
}
};
this.updateAll();
}
public render() {
const {appId} = this.state;
const {messagesStore, appStore} = this.props;
const [deleteAll, setDeleteAll] = React.useState(false);
const [isLoadingMore, setLoadingMore] = React.useState(false);
const {messagesStore, appStore} = useStores();
const messages = messagesStore.get(appId);
const hasMore = messagesStore.canLoadMore(appId);
const name = appStore.getName(appId);
const hasMessages = messages.length !== 0;
const expandedState = React.useRef<Record<number, boolean>>({});
const deleteMessage = (message: IMessage) => () => messagesStore.removeSingle(message);
React.useEffect(() => {
if (!messagesStore.loaded(appId)) {
messagesStore.loadMore(appId);
}
}, [appId]);
const renderMessage = (index: number, message: IMessage) => (
<Message
key={index}
fDelete={deleteMessage(message)}
onExpand={(expanded) => (expandedState.current[message.id] = expanded)}
title={message.title}
date={message.date}
appName={appStore.getName(message.appid)}
expanded={expandedState.current[message.id] ?? false}
content={message.message}
image={message.image}
extras={message.extras}
priority={message.priority}
/>
);
const checkIfLoadMore = () => {
if (!isLoadingMore && messagesStore.canLoadMore(appId)) {
setLoadingMore(true);
messagesStore.loadMore(appId).then(() => setLoadingMore(false));
}
};
const messageFooter = () => {
if (hasMore) {
return <LoadingSpinner />;
}
if (hasMessages) {
return label("You've reached the end");
}
return null;
};
const renderMessages = () => (
<Virtuoso
id="messages"
style={{width: '100%'}}
useWindowScroll
totalCount={messages.length}
endReached={checkIfLoadMore}
data={messages}
itemContent={renderMessage}
components={{
Footer: messageFooter,
EmptyPlaceholder: () => label('No messages'),
}}
/>
);
const label = (text: string) => (
<Grid size={{xs: 12}}>
<Typography variant="caption" component="div" gutterBottom align="center">
{text}
</Typography>
</Grid>
);
return (
<DefaultPage
title={name}
@ -81,88 +107,24 @@ class Messages extends Component<IProps & Stores<'messagesStore' | 'appStore'>,
disabled={!hasMessages}
color="primary"
onClick={() => {
this.deleteAll = true;
setDeleteAll(true);
}}>
Delete All
</Button>
</div>
}>
{!messagesStore.loaded(appId) ? (
<LoadingSpinner />
) : hasMessages ? (
<div style={{width: '100%'}} id="messages">
<ReactInfinite
key={appId}
useWindowAsScrollContainer
preloadBatchSize={window.innerHeight * 3}
elementHeight={messages.map((m) => this.heights[m.id] || 1)}>
{messages.map(this.renderMessage)}
</ReactInfinite>
{!messagesStore.loaded(appId) ? <LoadingSpinner /> : renderMessages()}
{hasMore ? <LoadingSpinner /> : this.label("You've reached the end")}
</div>
) : (
this.label('No messages')
)}
{this.deleteAll && (
{deleteAll && (
<ConfirmDialog
title="Confirm Delete"
text={'Delete all messages?'}
fClose={() => (this.deleteAll = false)}
fClose={() => setDeleteAll(false)}
fOnSubmit={() => messagesStore.removeByApp(appId)}
/>
)}
</DefaultPage>
);
}
});
private updateAllWithProps = (props: IProps & Stores<'messagesStore'>) => {
const appId = Messages.appId(props);
this.setState({appId});
if (!props.messagesStore.exists(appId)) {
props.messagesStore.loadMore(appId);
}
};
private updateAll = () => this.updateAllWithProps(this.props);
private deleteMessage = (message: IMessage) => () =>
this.props.messagesStore.removeSingle(message);
private renderMessage = (message: IMessage) => (
<Message
key={message.id}
height={(height: number) => {
if (!this.heights[message.id]) {
this.heights[message.id] = height;
}
}}
fDelete={this.deleteMessage(message)}
title={message.title}
date={message.date}
content={message.message}
image={message.image}
extras={message.extras}
priority={message.priority}
/>
);
private checkIfLoadMore() {
const {appId} = this.state;
if (!this.isLoadingMore && this.props.messagesStore.canLoadMore(appId)) {
this.isLoadingMore = true;
this.props.messagesStore.loadMore(appId).then(() => (this.isLoadingMore = false));
}
}
private label = (text: string) => (
<Grid item xs={12}>
<Typography variant="caption" component="div" gutterBottom align="center">
{text}
</Typography>
</Grid>
);
}
export default inject('messagesStore', 'appStore')(Messages);
export default Messages;

View File

@ -1,5 +1,5 @@
import {BaseStore} from '../common/BaseStore';
import {action, IObservableArray, observable, reaction} from 'mobx';
import {action, IObservableArray, observable, reaction, makeObservable} from 'mobx';
import axios, {AxiosResponse} from 'axios';
import * as config from '../config';
import {createTransformer} from 'mobx-utils';
@ -16,7 +16,6 @@ interface MessagesState {
}
export class MessagesStore {
@observable
private state: Record<string, MessagesState> = {};
private loading = false;
@ -25,6 +24,16 @@ export class MessagesStore {
private readonly appStore: BaseStore<IApplication>,
private readonly snack: SnackReporter
) {
makeObservable<MessagesStore, 'state'>(this, {
state: observable,
loadMore: action,
publishSingleMessage: action,
removeByApp: action,
removeSingle: action,
clearAll: action,
refreshByApp: action,
});
reaction(() => appStore.getItems(), this.createEmptyStatesForApps);
}
@ -39,7 +48,6 @@ export class MessagesStore {
public canLoadMore = (appId: number) => this.stateOf(appId, /*create*/ false).hasMore;
@action
public loadMore = async (appId: number) => {
const state = this.stateOf(appId);
if (!state.hasMore || this.loading) {
@ -47,19 +55,21 @@ export class MessagesStore {
}
this.loading = true;
try {
const pagedResult = await this.fetchMessages(appId, state.nextSince).then(
(resp) => resp.data
);
state.messages.replace([...state.messages, ...pagedResult.messages]);
state.nextSince = pagedResult.paging.since ?? 0;
state.hasMore = 'next' in pagedResult.paging;
state.loaded = true;
} finally {
this.loading = false;
}
return Promise.resolve();
};
@action
public publishSingleMessage = (message: IMessage) => {
if (this.exists(AllMessages)) {
this.stateOf(AllMessages).messages.unshift(message);
@ -69,7 +79,6 @@ export class MessagesStore {
}
};
@action
public removeByApp = async (appId: number) => {
if (appId === AllMessages) {
await axios.delete(config.get('url') + 'message');
@ -84,7 +93,6 @@ export class MessagesStore {
await this.loadMore(appId);
};
@action
public removeSingle = async (message: IMessage) => {
await axios.delete(config.get('url') + 'message/' + message.id);
if (this.exists(AllMessages)) {
@ -96,13 +104,11 @@ export class MessagesStore {
this.snack('Message deleted');
};
@action
public clearAll = () => {
this.state = {};
this.createEmptyStatesForApps(this.appStore.getItems());
};
@action
public refreshByApp = async (appId: number) => {
this.clearAll();
this.loadMore(appId);
@ -136,15 +142,17 @@ export class MessagesStore {
}
};
private getUnCached = (appId: number): Array<IMessage & {image: string | null}> => {
const appToImage = this.appStore
private getUnCached = (appId: number): Array<IMessage> => {
const appToImage: Partial<Record<string, string>> = this.appStore
.getItems()
.reduce((all, app) => ({...all, [app.id]: app.image}), {});
return this.stateOf(appId, false).messages.map((message: IMessage) => ({
return this.stateOf(appId, false).messages.map(
(message: IMessage): IMessage => ({
...message,
image: appToImage[message.appid] || null,
}));
image: appToImage[message.appid],
})
);
};
public get = createTransformer(this.getUnCached);

View File

@ -7,9 +7,7 @@ export enum RenderMode {
export const contentType = (extras?: IMessageExtras): RenderMode => {
const type = extract(extras, 'client::display', 'contentType');
const valid = Object.keys(RenderMode)
.map((k) => RenderMode[k])
.some((mode) => mode === type);
const valid = Object.values(RenderMode).includes(type);
return valid ? type : RenderMode.Plain;
};

View File

@ -1,78 +1,58 @@
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';
import 'codemirror/theme/material.css';
import 'codemirror/mode/yaml/yaml';
import Info from '@material-ui/icons/Info';
import Build from '@material-ui/icons/Build';
import Subject from '@material-ui/icons/Subject';
import Refresh from '@material-ui/icons/Refresh';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import {material} from '@uiw/codemirror-theme-material';
import CodeMirror from '@uiw/react-codemirror';
import Info from '@mui/icons-material/Info';
import Build from '@mui/icons-material/Build';
import Subject from '@mui/icons-material/Subject';
import Refresh from '@mui/icons-material/Refresh';
import Button from '@mui/material/Button';
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 +63,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 +75,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;
@ -126,7 +94,7 @@ interface IPanelWrapperProps {
icon?: React.ComponentType;
}
const PanelWrapper: React.FC<IPanelWrapperProps> = ({
const PanelWrapper: React.FC<React.PropsWithChildren<IPanelWrapperProps>> = ({
name,
description,
refresh,
@ -178,50 +146,39 @@ 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) => {
const ConfigurerPanel = ({initialConfig, save}: IConfigurerPanelProps) => {
const [unsavedChanges, setUnsavedChanges] = React.useState<string | null>(null);
const onChange = React.useCallback(
(value: string | null) => {
let newConf: string | null = value;
if (value === this.props.initialConfig) {
if (value === initialConfig) {
newConf = null;
}
this.setState({unsavedChanges: newConf});
}}
/>
setUnsavedChanges(newConf);
},
[initialConfig]
);
return (
<div>
<CodeMirror value={initialConfig} theme={material} onChange={onChange} />
<br />
<Button
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;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
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;
@ -233,13 +190,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 ? (
@ -284,7 +241,6 @@ class PluginInfo extends Component<{pluginInfo: IPlugin}> {
) : null}
</div>
);
}
}
};
export default inject('pluginStore')(PluginDetailView);
export default PluginDetailView;

View File

@ -1,5 +1,5 @@
import axios from 'axios';
import {action} from 'mobx';
import {action, makeObservable} from 'mobx';
import {BaseStore} from '../common/BaseStore';
import * as config from '../config';
import {SnackReporter} from '../snack/SnackManager';
@ -10,6 +10,11 @@ export class PluginStore extends BaseStore<IPlugin> {
public constructor(private readonly snack: SnackReporter) {
super();
makeObservable(this, {
changeConfig: action,
changeEnabledState: action,
});
}
public requestConfig = (id: number): Promise<string> =>
@ -31,7 +36,6 @@ export class PluginStore extends BaseStore<IPlugin> {
return id === -1 ? 'All Plugins' : plugin !== undefined ? plugin.name : 'unknown';
};
@action
public changeConfig = async (id: number, newConfig: string): Promise<void> => {
await axios.post(`${config.get('url')}plugin/${id}/config`, newConfig, {
headers: {'content-type': 'application/x-yaml'},
@ -40,7 +44,6 @@ export class PluginStore extends BaseStore<IPlugin> {
await this.refresh();
};
@action
public changeEnabledState = async (id: number, enabled: boolean): Promise<void> => {
await axios.post(`${config.get('url')}plugin/${id}/${enabled ? 'enable' : 'disable'}`);
this.snack(`Plugin ${enabled ? 'enabled' : 'disabled'}`);

View File

@ -1,32 +1,27 @@
import React, {Component, SFC} from 'react';
import React from 'react';
import {Link} from 'react-router-dom';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Settings from '@material-ui/icons/Settings';
import {Switch, Button} from '@material-ui/core';
import Grid from '@mui/material/Grid';
import Paper from '@mui/material/Paper';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Settings from '@mui/icons-material/Settings';
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}>
<Grid item xs={12}>
<Grid size={{xs: 12}}>
<Paper elevation={6} style={{overflowX: 'auto'}}>
<Table id="plugin-table">
<TableHead>
@ -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;
@ -71,7 +62,7 @@ interface IRowProps {
fToggleStatus: VoidFunction;
}
const Row: SFC<IRowProps> = observer(({name, id, token, enabled, fToggleStatus}) => (
const Row: React.FC<IRowProps> = observer(({name, id, token, enabled, fToggleStatus}) => (
<TableRow>
<TableCell>{id}</TableCell>
<TableCell>
@ -96,4 +87,4 @@ const Row: SFC<IRowProps> = observer(({name, id, token, enabled, fToggleStatus})
</TableRow>
));
export default inject('pluginStore')(Plugins);
export default Plugins;

View File

@ -1,6 +1,6 @@
import {StoreMapping} from './inject';
import {reaction} from 'mobx';
import * as Notifications from './snack/browserNotification';
import {StoreMapping} from './stores';
export const registerReactions = (stores: StoreMapping) => {
const clearAll = () => {
@ -40,6 +40,7 @@ export const registerReactions = (stores: StoreMapping) => {
if (!connectionErrorMessage) {
clearAll();
loadAll();
stores.currentUser.refreshKey++;
}
}
);

View File

@ -1 +0,0 @@
jest.setTimeout(process.env.CI === 'true' ? 50000 : 20000);

View File

@ -1,83 +0,0 @@
import IconButton from '@material-ui/core/IconButton';
import Snackbar from '@material-ui/core/Snackbar';
import Close from '@material-ui/icons/Close';
import React, {Component} from 'react';
import {observable, reaction} from 'mobx';
import {observer} from 'mobx-react';
import {inject, Stores} from '../inject';
@observer
class SnackBarHandler extends Component<Stores<'snackManager'>> {
private static MAX_VISIBLE_SNACK_TIME_IN_MS = 6000;
private static MIN_VISIBLE_SNACK_TIME_IN_MS = 1000;
@observable
private open = false;
@observable
private openWhen = 0;
private dispose: () => void = () => {};
public componentDidMount = () =>
(this.dispose = reaction(() => this.props.snackManager.counter, this.onNewSnack));
public componentWillUnmount = () => this.dispose();
public render() {
const {message: current, hasNext} = this.props.snackManager;
const duration = hasNext()
? SnackBarHandler.MIN_VISIBLE_SNACK_TIME_IN_MS
: SnackBarHandler.MAX_VISIBLE_SNACK_TIME_IN_MS;
return (
<Snackbar
anchorOrigin={{vertical: 'bottom', horizontal: 'left'}}
open={this.open}
autoHideDuration={duration}
onClose={this.closeCurrentSnack}
onExited={this.openNextSnack}
message={<span id="message-id">{current}</span>}
action={
<IconButton
key="close"
aria-label="Close"
color="inherit"
onClick={this.closeCurrentSnack}>
<Close />
</IconButton>
}
/>
);
}
private onNewSnack = () => {
const {open, openWhen} = this;
if (!open) {
this.openNextSnack();
return;
}
const snackOpenSince = Date.now() - openWhen;
if (snackOpenSince > SnackBarHandler.MIN_VISIBLE_SNACK_TIME_IN_MS) {
this.closeCurrentSnack();
} else {
setTimeout(
this.closeCurrentSnack,
SnackBarHandler.MIN_VISIBLE_SNACK_TIME_IN_MS - snackOpenSince
);
}
};
private openNextSnack = () => {
if (this.props.snackManager.hasNext()) {
this.open = true;
this.openWhen = Date.now();
this.props.snackManager.next();
}
};
private closeCurrentSnack = () => (this.open = false);
}
export default inject('snackManager')(SnackBarHandler);

View File

@ -1,30 +1,11 @@
import {action, observable} from 'mobx';
import {enqueueSnackbar} from 'notistack';
export interface SnackReporter {
(message: string): void;
}
export class SnackManager {
@observable
private messages: string[] = [];
@observable
public message: string | null = null;
@observable
public counter = 0;
@action
public next = (): void => {
if (!this.hasNext()) {
throw new Error('There is nothing here :(');
}
this.message = this.messages.shift() as string;
};
public hasNext = () => this.messages.length > 0;
@action
public snack: SnackReporter = (message: string): void => {
this.messages.push(message);
this.counter++;
enqueueSnackbar({message, variant: 'info'});
};
}

View File

@ -5,7 +5,6 @@ import {MessagesStore} from './message/MessagesStore';
import {CurrentUser} from './CurrentUser';
import {ClientStore} from './client/ClientStore';
import {AppStore} from './application/AppStore';
import {inject as mobxInject, Provider} from 'mobx-react';
import {WebSocketStore} from './message/WebSocketStore';
import {PluginStore} from './plugin/PluginStore';
@ -20,18 +19,10 @@ export interface StoreMapping {
wsStore: WebSocketStore;
}
export type AllStores = Extract<keyof StoreMapping, string>;
export type Stores<T extends AllStores> = Pick<StoreMapping, T>;
export const StoreContext = React.createContext<StoreMapping | undefined>(undefined);
export const inject =
<I extends AllStores>(...stores: I[]) =>
// eslint-disable-next-line @typescript-eslint/ban-types
<P extends {}>(
node: React.ComponentType<P>
): React.ComponentType<Pick<P, Exclude<keyof P, I>>> =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mobxInject(...stores)(node) as any;
export const InjectProvider: React.FC<{stores: StoreMapping}> = ({children, stores}) => (
<Provider {...stores}>{children}</Provider>
);
export const useStores = (): StoreMapping => {
const mapping = React.useContext(StoreContext);
if (!mapping) throw new Error('uninitialized');
return mapping;
};

View File

@ -1,6 +1,7 @@
import {Page} from 'puppeteer';
import {newTest, GotifyTest} from './setup';
import {count, innerText, waitForExists, waitToDisappear, clearField} from './utils';
import {afterAll, beforeAll, describe, expect, it} from 'vitest';
import * as auth from './authentication';
import * as selector from './selector';
@ -63,6 +64,7 @@ const createApp =
await page.type($dialog.input('.name'), name);
await page.type($dialog.textarea('.description'), description);
await page.click($dialog.button('.create'));
await waitToDisappear(page, $dialog.selector());
};
describe('Application', () => {

View File

@ -1,5 +1,6 @@
import {Page} from 'puppeteer';
import {waitForExists} from './utils';
import {expect} from 'vitest';
import * as selector from './selector';
const $loginForm = selector.form('#login-form');

View File

@ -1,6 +1,7 @@
import {Page} from 'puppeteer';
import {newTest, GotifyTest} from './setup';
import {count, innerText, waitForExists, waitToDisappear, clearField} from './utils';
import {afterAll, beforeAll, describe, expect, it} from 'vitest';
import * as auth from './authentication';
import * as selector from './selector';
@ -65,6 +66,7 @@ describe('Client', () => {
await page.waitForSelector($dialog.selector());
await page.type($dialog.input('.name'), name);
await page.click($dialog.button('.create'));
await waitToDisappear(page, $dialog.selector());
};
it('phone', createClient('phone'));
it('desktop app', createClient('desktop app'));
@ -98,7 +100,6 @@ describe('Client', () => {
expect(await count(page, $table.rows())).toBe(2);
});
// eslint-disable-next-line
it('deletes own client', async () => {
await page.click($table.cell(1, Col.Delete, '.delete'));

View File

@ -2,6 +2,7 @@
import {Page} from 'puppeteer';
import {newTest, GotifyTest} from './setup';
import {clickByText, count, innerText, waitForCount, waitForExists} from './utils';
import {afterAll, beforeAll, describe, expect, it} from 'vitest';
import * as auth from './authentication';
import * as selector from './selector';
import axios from 'axios';
@ -16,7 +17,6 @@ beforeAll(async () => {
afterAll(async () => await gotify.close());
// eslint-disable-next-line
const axiosAuth = {auth: {username: 'admin', password: 'admin'}};
let windowsServerToken: string;
@ -35,7 +35,6 @@ const navigate = async (appName: string) => {
await waitForExists(page, selector.heading(), appName);
};
// eslint-disable-next-line
describe('Messages', () => {
it('does login', async () => await auth.login(page));
it('is on messages', async () => {
@ -83,11 +82,11 @@ describe('Messages', () => {
await navigate('All Messages');
});
it('has no messages', async () => {
expect(await count(page, '#messages')).toBe(0);
expect(await count(page, '#messages .message')).toBe(0);
});
it('has no messages in app', async () => {
await navigate('Windows');
expect(await count(page, '#messages')).toBe(0);
expect(await count(page, '#messages .message')).toBe(0);
await navigate('All Messages');
});

View File

@ -1,7 +1,7 @@
import * as os from 'os';
import {Page} from 'puppeteer';
import axios from 'axios';
import {afterAll, beforeAll, describe, expect, it} from 'vitest';
import * as auth from './authentication';
import * as selector from './selector';
import {GotifyTest, newTest, newPluginDir} from './setup';
@ -57,6 +57,7 @@ const getDisplayer = async () => await innerText(page, '.displayer');
const hasReceivedMessage = async (title: RegExp, content: RegExp) => {
await page.click('#message-navigation a');
await waitForExists(page, selector.heading(), 'All Messages');
await waitForCount(page, '#messages .message', 1);
expect(await innerText(page, '.title')).toMatch(title);
expect(await innerText(page, '.content')).toMatch(content);
@ -136,11 +137,11 @@ describe('plugin', () => {
await (await page.$('.config-save'))!.getProperty('disabled')
).jsonValue()
).toBe(true);
await page.waitForSelector('.CodeMirror .CodeMirror-code');
await page.waitForSelector('.cm-editor .cm-content');
await page.waitForFunction(
'document.querySelector(".CodeMirror .CodeMirror-code").innerText.toLowerCase().indexOf("loading")<0'
'document.querySelector(".cm-editor .cm-content").innerText.toLowerCase().indexOf("loading")<0'
);
await page.click('.CodeMirror .CodeMirror-code > div');
await page.click('.cm-editor .cm-content > div');
await page.keyboard.press('x');
await page.waitForFunction(
'document.querySelector(".config-save") && !document.querySelector(".config-save").disabled'
@ -156,13 +157,11 @@ describe('plugin', () => {
await (await page.$('.config-save'))!.getProperty('disabled')
).jsonValue()
).toBe(true);
await page.waitForSelector('.CodeMirror .CodeMirror-code > div');
await page.waitForSelector('.cm-editor .cm-content > div');
await page.waitForFunction(
'document.querySelector(".CodeMirror .CodeMirror-code > div").innerText.toLowerCase().indexOf("loading")<0'
);
expect(await innerText(page, '.CodeMirror .CodeMirror-code > div')).toMatch(
/x$/
'document.querySelector(".cm-editor .cm-content > div").innerText.toLowerCase().indexOf("loading")<0'
);
expect(await innerText(page, '.cm-editor .cm-content > div')).toMatch(/x$/);
});
});
it('sends messages', async () => {
@ -172,6 +171,9 @@ describe('plugin', () => {
await inDetailPage(1, async () => {
await page.waitForSelector('.displayer a');
const hook = await page.$eval('.displayer a', (el) => el.getAttribute('href'));
if (!hook) {
throw 'href not found';
}
await axios.get(hook);
});
});

View File

@ -1,10 +1,10 @@
import getPort from 'get-port';
import {spawn, exec, ChildProcess} from 'child_process';
import rimraf from 'rimraf';
import {rimrafSync} from 'rimraf';
import path from 'path';
import puppeteer, {Browser, Page} from 'puppeteer';
import fs from 'fs';
// @ts-ignore
// @ts-expect-error no types
import wait from 'wait-on';
import kill from 'tree-kill';
@ -50,9 +50,11 @@ export const newTest = async (pluginsDir = ''): Promise<GotifyTest> => {
close: async () => {
await Promise.all([
browser.close(),
new Promise((resolve) => kill(gotifyInstance.pid!, 'SIGKILL', () => resolve())),
new Promise((resolve) =>
kill(gotifyInstance.pid!, 'SIGKILL', () => resolve(undefined))
),
]);
rimraf.sync(gotifyFile, {maxBusyTries: 8});
rimrafSync(gotifyFile, {maxRetries: 8});
},
url: gotifyURL,
browser,

View File

@ -1,6 +1,7 @@
import {Page} from 'puppeteer';
import {newTest, GotifyTest} from './setup';
import {clearField, count, innerText, waitForExists, waitToDisappear} from './utils';
import {afterAll, beforeAll, describe, expect, it} from 'vitest';
import * as auth from './authentication';
import * as selector from './selector';

View File

@ -59,7 +59,7 @@ export const waitForExists = async (page: Page, selector: string, text: string):
export const clearField = async (element: ElementHandle | Page, selector: string) => {
const elementHandle = await element.$(selector);
if (!elementHandle) {
fail();
throw 'element handle not set';
}
await elementHandle.click();
await elementHandle.focus();

View File

@ -1,3 +1,4 @@
// eslint-disable-next-line
import Notify = require('notifyjs');
export as namespace notifyjs;
export = Notify;

View File

@ -1,9 +1,19 @@
declare module 'react-timeago' {
import React from 'react';
export type FormatterOptions = {
style?: 'long' | 'short' | 'narrow';
};
export type Formatter = (options: FormatterOptions) => React.ReactNode;
export interface ITimeAgoProps {
date: string;
formatter?: Formatter;
}
export default class TimeAgo extends React.Component<ITimeAgoProps, unknown> {}
}
declare module 'react-timeago/defaultFormatter' {
declare function makeIntlFormatter(options: FormatterOptions): Formatter;
}

View File

@ -1,42 +1,37 @@
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Switch from '@material-ui/core/Switch';
import TextField from '@material-ui/core/TextField';
import Tooltip from '@material-ui/core/Tooltip';
import React, {ChangeEvent, Component} from 'react';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogTitle from '@mui/material/DialogTitle';
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 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: string, event: ChangeEvent<HTMLInputElement>) {
const state = this.state;
state[propertyName] = event.target.value;
this.setState(state);
}
private handleChecked(propertyName: string, event: ChangeEvent<HTMLInputElement>) {
const state = this.state;
state[propertyName] = event.target.checked;
this.setState(state);
}
}
};
export default AddEditUserDialog;

View File

@ -1,31 +1,48 @@
import Button from '@material-ui/core/Button';
import Grid from '@material-ui/core/Grid';
import TextField from '@material-ui/core/TextField';
import React, {Component, FormEvent} from 'react';
import Button from '@mui/material/Button';
import Grid from '@mui/material/Grid';
import TextField from '@mui/material/TextField';
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';
import {useNavigate} from 'react-router';
@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 navigate = useNavigate();
React.useEffect(() => {
if (currentUser.loggedIn) {
navigate('/');
}
}, [currentUser.loggedIn]);
const registerButton = () => {
if (config.get('register'))
return (
<DefaultPage title="Login" rightControl={this.registerButton()} maxWidth={250}>
<Grid item xs={12} style={{textAlign: 'center'}}>
<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 +52,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 +63,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 +71,12 @@ class Login extends Component<Stores<'currentUser'>> {
size="large"
className="login"
color="primary"
disabled={!!this.props.currentUser.connectionErrorMessage}
disabled={
!!currentUser.connectionErrorMessage || currentUser.authenticating
}
style={{marginTop: 15, marginBottom: 5}}
onClick={this.login}>
loading={currentUser.authenticating}
onClick={login}>
Login
</Button>
</form>
@ -64,34 +84,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

@ -1,11 +1,11 @@
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import TextField from '@material-ui/core/TextField';
import Tooltip from '@material-ui/core/Tooltip';
import React, {ChangeEvent, Component} from 'react';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
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 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: string, event: ChangeEvent<HTMLInputElement>) {
const state = this.state;
state[propertyName] = event.target.value;
this.setState(state);
}
}
};
export default RegistrationDialog;

View File

@ -1,13 +1,18 @@
import {BaseStore} from '../common/BaseStore';
import axios from 'axios';
import * as config from '../config';
import {action} from 'mobx';
import {action, makeObservable} from 'mobx';
import {SnackReporter} from '../snack/SnackManager';
import {IUser} from '../types';
export class UserStore extends BaseStore<IUser> {
constructor(private readonly snack: SnackReporter) {
super();
makeObservable(this, {
create: action,
update: action,
});
}
protected requestItems = (): Promise<IUser[]> =>
@ -19,14 +24,12 @@ export class UserStore extends BaseStore<IUser> {
.then(() => this.snack('User deleted'));
}
@action
public create = async (name: string, pass: string, admin: boolean) => {
await axios.post(`${config.get('url')}user`, {name, pass, admin});
await this.refresh();
this.snack('User created');
};
@action
public update = async (id: number, name: string, pass: string | null, admin: boolean) => {
await axios.post(config.get('url') + 'user/' + id, {name, pass, admin});
await this.refresh();

View File

@ -1,30 +1,21 @@
import Grid from '@material-ui/core/Grid';
import IconButton from '@material-ui/core/IconButton';
import Paper from '@material-ui/core/Paper';
import {withStyles, WithStyles} from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Delete from '@material-ui/icons/Delete';
import Edit from '@material-ui/icons/Edit';
import React, {Component, SFC} from 'react';
import Grid from '@mui/material/Grid';
import IconButton from '@mui/material/IconButton';
import Paper from '@mui/material/Paper';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
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 from 'react';
import ConfirmDialog from '../common/ConfirmDialog';
import DefaultPage from '../common/DefaultPage';
import Button from '@material-ui/core/Button';
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';
const styles = () => ({
wrapper: {
margin: '0 auto',
maxWidth: 700,
},
});
import {useStores} from '../stores';
import {observer} from 'mobx-react';
interface IRowProps {
name: string;
@ -33,39 +24,27 @@ 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>
<TableCell align="right" padding="none">
<IconButton onClick={fEdit} className="edit">
<IconButton onClick={fEdit} className="edit" size="large">
<Edit />
</IconButton>
<IconButton onClick={fDelete} className="delete">
<IconButton onClick={fDelete} className="delete" size="large">
<Delete />
</IconButton>
</TableCell>
</TableRow>
);
@observer
class Users extends Component<WithStyles<'wrapper'> & 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
@ -75,11 +54,11 @@ class Users extends Component<WithStyles<'wrapper'> & Stores<'userStore'>> {
id="create-user"
variant="contained"
color="primary"
onClick={() => (this.createDialog = true)}>
onClick={() => setCreateDialog(true)}>
Create User
</Button>
}>
<Grid item xs={12}>
<Grid size={{xs: 12}}>
<Paper elevation={6} style={{overflowX: 'auto'}}>
<Table id="user-table">
<TableHead>
@ -95,8 +74,8 @@ class Users extends Component<WithStyles<'wrapper'> & 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>
@ -104,31 +83,27 @@ class Users extends Component<WithStyles<'wrapper'> & 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 withStyles(styles)(inject('userStore')(Users));
export default Users;

View File

@ -1,12 +1,9 @@
{
"compilerOptions": {
"baseUrl": "src",
"outDir": "build/dist",
"target": "es5",
"lib": [
"es6",
"dom"
],
"target": "ES2020",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"allowImportingTsExtensions": true,
"sourceMap": true,
"allowJs": true,
"jsx": "react",
@ -17,10 +14,8 @@
"noImplicitThis": true,
"noImplicitAny": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": true,
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"esModuleInterop": true,
"strict": true,
@ -28,7 +23,6 @@
"noEmit": true,
"module": "esnext",
"resolveJsonModule": true,
"keyofStringsOnly": true,
"noFallthroughCasesInSwitch": true
},
"exclude": [

2
ui/vite-env.d.ts vendored Normal file
View File

@ -0,0 +1,2 @@
// Example: vite-env.d.ts
/// <reference types="vite/client" />

36
ui/vite.config.ts Normal file
View File

@ -0,0 +1,36 @@
import {defineConfig} from 'vite';
import react from '@vitejs/plugin-react';
const GOTIFY_SERVER_PORT = process.env.GOTIFY_SERVER_PORT ?? '80';
export default defineConfig({
build: {
outDir: 'build',
emptyOutDir: true,
sourcemap: false,
assetsDir: 'static',
},
plugins: [react()],
define: {
// Some libraries use the global object, even though it doesn't exist in the browser.
// Alternatively, we could add `<script>window.global = window;</script>` to index.html.
// https://github.com/vitejs/vite/discussions/5912
global: {},
},
server: {
host: '0.0.0.0',
proxy: {
'^/(application|message|client|current|user|plugin|version|image)': {
target: `http://localhost:${GOTIFY_SERVER_PORT}/`,
changeOrigin: true,
secure: false,
},
'/stream': {
target: `ws://localhost:${GOTIFY_SERVER_PORT}/`,
ws: true,
rewriteWsOrigin: true,
},
},
cors: false,
},
});

10
ui/vitest.config.js Normal file
View File

@ -0,0 +1,10 @@
import {defineConfig} from 'vitest/config';
const timeout = process.env.CI === 'true' ? 60000 : 30000;
export default defineConfig({
test: {
testTimeout: timeout,
hookTimeout: timeout,
},
});

14818
ui/yarn.lock

File diff suppressed because it is too large Load Diff