58 lines
1.9 KiB
TypeScript
58 lines
1.9 KiB
TypeScript
import React from 'react'
|
|
import { resolveActiveLocale, t } from '../i18n'
|
|
import { events } from '../wails'
|
|
|
|
interface State {
|
|
error: Error | null
|
|
stack: string
|
|
}
|
|
|
|
/**
|
|
* Top-level React error boundary: prevents any uncaught render/lifecycle error
|
|
* from unmounting the entire tree into an unrecoverable blank white screen,
|
|
* reports the stack trace to the Go backend log, and offers a one-click reload.
|
|
*/
|
|
export class ErrorBoundary extends React.Component<{ children: React.ReactNode }, State> {
|
|
state: State = { error: null, stack: '' }
|
|
|
|
static getDerivedStateFromError(error: Error): Partial<State> {
|
|
return { error }
|
|
}
|
|
|
|
componentDidCatch(error: Error, info: React.ErrorInfo): void {
|
|
const stack = [error.stack, info.componentStack].filter(Boolean).join('\n').trim()
|
|
this.setState({ stack })
|
|
events.emitUIError(`ReactErrorBoundary: ${error.message}\n${stack.slice(0, 1500)}`)
|
|
}
|
|
|
|
render(): React.ReactNode {
|
|
const { error, stack } = this.state
|
|
if (!error) return this.props.children
|
|
|
|
const docLocale = typeof document !== 'undefined' ? document.documentElement.dataset.locale : undefined
|
|
const loc = resolveActiveLocale(docLocale || undefined)
|
|
return (
|
|
<div className="error-boundary">
|
|
<div className="error-boundary-card" role="alert">
|
|
<h2 className="error-boundary-title">
|
|
{t(loc, 'errorBoundaryTitle')}
|
|
</h2>
|
|
<pre className="error-boundary-pre selectable">
|
|
{error.message || String(error)}
|
|
{stack ? `\n\n${stack}` : ''}
|
|
</pre>
|
|
<div className="error-boundary-actions">
|
|
<button
|
|
type="button"
|
|
className="btn rg-p-button btn-primary"
|
|
onClick={() => window.location.reload()}
|
|
>
|
|
{t(loc, 'errorBoundaryReload')}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|
|
}
|