Create async widget

This commit is contained in:
2021-05-10 19:03:42 +02:00
parent d02ab79f50
commit 1b683d7b77
5 changed files with 142 additions and 13 deletions

View File

@ -0,0 +1,81 @@
/**
* Asynchronous loading widget
*
* @author Pierre Hubert
*/
import { Button, Paper } from "@material-ui/core";
import React, { ReactNode } from "react";
import { CenterCircularProgress } from "./CenterCircularProgress";
enum Status {
LOADING,
ERROR,
SUCCESS
}
export interface AsyncWidgetProperties {
load: () => Promise<void>,
errorMessage: string,
onBuild: () => ReactNode
}
interface AsyncWidgetState {
status: Status,
}
export class AsyncWidget extends React.Component<AsyncWidgetProperties, AsyncWidgetState> {
constructor(props: any) {
super(props);
this.state = {
status: Status.LOADING
}
this.reload = this.reload.bind(this);
}
async reload() {
try {
this.setState({status: Status.LOADING});
await this.props.load();
this.setState({status: Status.SUCCESS});
} catch(e) {
console.error(e);
this.setState({status: Status.ERROR});
}
}
componentDidMount() {
this.reload()
}
render() {
if (this.state.status == Status.ERROR)
return (<div style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
height: "100%",
}}>
<Paper>
<div style={{padding: "5px 10px"}}>
{this.props.errorMessage}
&nbsp;
<Button onClick={this.reload}>Try again</Button>
</div>
</Paper>
</div>);
if(this.state.status == Status.SUCCESS)
return this.props.onBuild();
return (<CenterCircularProgress></CenterCircularProgress>)
}
}

View File

@ -0,0 +1,12 @@
import { CircularProgress } from "@material-ui/core";
export function CenterCircularProgress() {
return <div style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "100%"
}}>
<CircularProgress></CircularProgress>
</div>
}

View File

@ -0,0 +1,39 @@
/**
* Initialization widget
*
* @author Pierre Hubert
*/
import React from "react";
import { AsyncWidget } from "./AsyncWidget";
export class InitWidget extends React.Component {
constructor(props: any) {
super(props);
this.init = this.init.bind(this);
this.build = this.build.bind(this);
}
async init() {
await new Promise((res, rej) => {
setTimeout(() => {
rej(null);
}, 500)
})
}
render() {
return (<AsyncWidget
errorMessage = "Failed to initialize application!"
load = {this.init}
onBuild = {this.build}
></AsyncWidget>);
}
build() {
return (<div>yes !!! done !!!</div>);
}
}