import React, { Component } from "react"; import { cn } from "../../lib/utils"; type LazyLoadBoundaryProps = { children: React.ReactNode; className?: string; fallback?: React.ReactNode | ((error: Error) => React.ReactNode); name?: string; resetKey?: React.Key | null; }; type LazyLoadBoundaryState = { error: Error | null; retryKey: number; }; export class LazyLoadBoundary extends Component { declare props: Readonly; declare setState: React.Component["setState"]; state: LazyLoadBoundaryState = { error: null, retryKey: 0 }; static getDerivedStateFromError(error: Error): Partial { return { error }; } componentDidUpdate(prevProps: LazyLoadBoundaryProps) { if (prevProps.resetKey !== this.props.resetKey && this.state.error) { this.setState({ error: null }); } } private retry = () => { if (typeof window !== "undefined" && typeof window.location?.reload === "function") { window.location.reload(); return; } this.setState(({ retryKey }) => ({ error: null, retryKey: retryKey + 1 })); }; componentDidCatch(error: Error, errorInfo: React.ErrorInfo) { console.error(`[LazyLoadBoundary] ${this.props.name || "content"} failed:`, error, errorInfo.componentStack); } render() { if (this.state.error) { const { fallback } = this.props; if (typeof fallback === "function") return fallback(this.state.error); if (fallback) return fallback; const label = this.props.name || "This area"; return (
{label} could not load.
); } return {this.props.children}; } }