bitburner-src/src/ui/React/ErrorBoundary.tsx

100 lines
2.2 KiB
TypeScript
Raw Normal View History

/**
* React Component for a simple Error Boundary. The fallback UI for
* this error boundary is simply a bordered text box
*/
import * as React from "react";
import { EventEmitter } from "../../utils/EventEmitter";
type IProps = {
2021-09-05 01:09:30 +02:00
eventEmitterForReset?: EventEmitter;
id?: string;
};
type IState = {
2021-09-05 01:09:30 +02:00
errorInfo: string;
hasError: boolean;
};
type IErrorInfo = {
2021-09-05 01:09:30 +02:00
componentStack: string;
};
// TODO: Move this out to a css file
const styleMarkup = {
2021-09-05 01:09:30 +02:00
border: "1px solid red",
display: "inline-block",
margin: "4px",
padding: "4px",
};
export class ErrorBoundary extends React.Component<IProps, IState> {
2021-09-05 01:09:30 +02:00
constructor(props: IProps) {
super(props);
this.state = {
errorInfo: "",
hasError: false,
};
}
2021-09-05 01:09:30 +02:00
componentDidCatch(error: Error, info: IErrorInfo): void {
console.error(`Caught error in React ErrorBoundary. Component stack:`);
console.error(info.componentStack);
}
2021-09-05 01:09:30 +02:00
componentDidMount(): void {
const cb = (): void => {
this.setState({
hasError: false,
});
};
2021-09-05 01:09:30 +02:00
if (this.hasEventEmitter()) {
(this.props.eventEmitterForReset as EventEmitter).addSubscriber({
cb: cb,
id: this.props.id as string,
});
}
2021-09-05 01:09:30 +02:00
}
2021-09-05 01:09:30 +02:00
componentWillUnmount(): void {
if (this.hasEventEmitter()) {
(this.props.eventEmitterForReset as EventEmitter).removeSubscriber(
this.props.id as string,
);
}
2021-09-05 01:09:30 +02:00
}
2021-09-05 01:09:30 +02:00
hasEventEmitter(): boolean {
return (
this.props.eventEmitterForReset != null &&
this.props.eventEmitterForReset instanceof EventEmitter &&
this.props.id != null &&
typeof this.props.id === "string"
);
}
2021-09-05 01:09:30 +02:00
render(): React.ReactNode {
if (this.state.hasError) {
return (
<div style={styleMarkup}>
<p>
{`Error rendering UI. This is (probably) a bug. Please report to game developer.`}
</p>
<p>{`In the meantime, try refreshing the game WITHOUT saving.`}</p>
<p>{`Error info: ${this.state.errorInfo}`}</p>
</div>
);
}
2021-05-01 09:17:31 +02:00
2021-09-05 01:09:30 +02:00
return this.props.children;
}
static getDerivedStateFromError(error: Error): IState {
return {
errorInfo: error.message,
hasError: true,
};
}
}