21 lines
1.6 KiB
TypeScript
21 lines
1.6 KiB
TypeScript
import {Component,type ReactNode} from 'react';
|
|
import {Button,SettingsCard} from '@nodedc/ui-react';
|
|
|
|
export function runtimeDiagnostic(error:unknown,code='ui-error') {
|
|
const kind=error instanceof Error&&/^[A-Za-z]{1,48}$/.test(error.name)?error.name:'Error';
|
|
// Never send exception messages, URLs, form values or arbitrary stack text.
|
|
const locations=error instanceof Error?(error.stack??'').match(/[A-Za-z0-9_-]+\.js:\d+:\d+/g)?.slice(0,8)??[]:[];
|
|
void fetch('/api/monitor/events',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({code,kind,locations}),keepalive:true}).catch(()=>{});
|
|
}
|
|
export function observeRuntime(){
|
|
window.addEventListener('error',event=>runtimeDiagnostic(event.error));
|
|
window.addEventListener('unhandledrejection',event=>runtimeDiagnostic(event.reason,'ui-rejection'));
|
|
}
|
|
export class RuntimeBoundary extends Component<{children:ReactNode;resetKey?:string},{failed:boolean}> {
|
|
state={failed:false};
|
|
static getDerivedStateFromError(){return {failed:true};}
|
|
componentDidCatch(error:Error){runtimeDiagnostic(error,'ui-render-error');}
|
|
componentDidUpdate(previous:Readonly<{children:ReactNode;resetKey?:string}>){if(this.state.failed&&previous.resetKey!==this.props.resetKey)this.setState({failed:false});}
|
|
render(){return this.state.failed?<SettingsCard title="Не удалось открыть представление" description="Вернитесь к устройствам или повторите открытие."><Button onClick={()=>this.setState({failed:false})}>Открыть повторно</Button></SettingsCard>:this.props.children;}
|
|
}
|