Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

6.2 KB
Raw Blame
import React, { Component, ErrorInfo, ReactNode } from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { markIntentionalReload } from "./utils/reloadGuard";
import { t } from "./i18n";
import "./index.css";

interface Props {
  children: ReactNode;
}

interface State {
  hasError: boolean;
  error: Error | null;
  componentStack: string | null;
  copied: boolean;
}

export class ErrorBoundary extends Component<Props, State> {
  private copyTimer: ReturnType<typeof setTimeout> | null = null;

  public state: State = {
    hasError: false,
    error: null,
    componentStack: null,
    copied: false,
  };

  public static getDerivedStateFromError(error: Error): State {
    return {
      hasError: true,
      error,
      componentStack: null,
      copied: false,
    };
  }

  public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error("Uncaught runtime error:", error, errorInfo);
    const stack = errorInfo?.componentStack?.trim() || null;
    if (stack) {
      this.setState({ componentStack: stack });
    }
  }

  public componentWillUnmount() {
    if (this.copyTimer !== null) {
      clearTimeout(this.copyTimer);
      this.copyTimer = null;
    }
  }

  private buildErrorDetailsText(): string {
    const err = this.state.error;
    const sections: string[] = [];
    sections.push(
      `Error: ${err?.name || "Error"}: ${err?.message || "An unexpected error occurred."}`
    );
    if (err?.stack) {
      sections.push(`\nStack Trace:\n${err.stack.trim()}`);
    }
    if (this.state.componentStack) {
      sections.push(`\nComponent Stack:\n${this.state.componentStack}`);
    }
    return sections.join("\n");
  }

  private handleCopyDetails = async () => {
    const details = this.buildErrorDetailsText();
    let ok = false;
    try {
      if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
        await navigator.clipboard.writeText(details);
        ok = true;
      }
    } catch {
      ok = false;
    }
    if (!ok && typeof document !== "undefined") {
      try {
        const ta = document.createElement("textarea");
        ta.value = details;
        ta.style.position = "fixed";
        ta.style.opacity = "0";
        document.body.appendChild(ta);
        ta.select();
        ok = document.execCommand("copy");
        document.body.removeChild(ta);
      } catch {
        ok = false;
      }
    }
    if (ok) {
      this.setState({ copied: true });
      if (this.copyTimer !== null) clearTimeout(this.copyTimer);
      this.copyTimer = setTimeout(() => {
        this.copyTimer = null;
        this.setState({ copied: false });
      }, 2000);
    }
  };

  public render() {
    if (this.state.hasError) {
      const errorStack = this.state.error?.stack?.trim() || null;
      const componentStack = this.state.componentStack;

      return (
        <div className="flex flex-col items-center justify-center w-screen h-screen bg-[#1e1e1e] text-[#cccccc] p-8 text-center font-sans select-none">
          <div className="bg-[#252525] border border-red-500/40 rounded-lg p-6 max-w-xl w-full shadow-2xl">
            <h2 className="text-lg font-bold text-red-400 mb-2">
              {t('Graphics Editor Encountered an Error')}
            </h2>
            <p className="text-xs text-[#a0a0a0] mb-4 font-mono break-all select-text">
              {this.state.error?.message || t('An unexpected error occurred.')}
            </p>

            {(errorStack || componentStack) && (
              <details className="text-left mb-4 bg-[#1a1a1a] border border-white/10 rounded p-2.5">
                <summary className="text-[11px] font-medium text-[#b0b0b0] hover:text-white cursor-pointer select-none">
                  {t('Error Details & Stack Trace')}
                </summary>
                <div className="mt-2 space-y-2 max-h-56 overflow-auto select-text">
                  {errorStack && (
                    <div>
                      <div className="text-[10px] uppercase tracking-wider text-[#888888] mb-0.5">
                        {t('Stack Trace')}
                      </div>
                      <pre className="text-[10px] leading-relaxed text-[#d4d4d4] font-mono whitespace-pre-wrap break-words">
                        {errorStack}
                      </pre>
                    </div>
                  )}
                  {componentStack && (
                    <div>
                      <div className="text-[10px] uppercase tracking-wider text-[#888888] mb-0.5">
                        {t('Component Stack')}
                      </div>
                      <pre className="text-[10px] leading-relaxed text-[#9ca3af] font-mono whitespace-pre-wrap break-words">
                        {componentStack}
                      </pre>
                    </div>
                  )}
                </div>
              </details>
            )}

            <div className="flex items-center justify-center gap-2">
              <button
                type="button"
                onClick={this.handleCopyDetails}
                className="px-3.5 py-1.5 bg-[#333333] hover:bg-[#3f3f3f] border border-white/10 text-[#e0e0e0] rounded text-xs font-medium transition-colors cursor-pointer"
              >
                {this.state.copied ? t('Copied Error Details') : t('Copy Error Details')}
              </button>
              <button
                type="button"
                onClick={() => {
                  this.setState({
                    hasError: false,
                    error: null,
                    componentStack: null,
                    copied: false,
                  });
                  markIntentionalReload();
                  window.location.reload();
                }}
                className="px-4 py-1.5 bg-blue-600 hover:bg-blue-500 text-white rounded text-xs font-medium transition-colors cursor-pointer"
              >
                {t('Reload Editor')}
              </button>
            </div>
          </div>
        </div>
      );
    }

    return this.props.children;
  }
}

const rootElement = typeof document !== "undefined" ? document.getElementById("root") : null;
if (rootElement) {
  ReactDOM.createRoot(rootElement).render(
    <React.StrictMode>
      <ErrorBoundary>
        <App />
      </ErrorBoundary>
    </React.StrictMode>,
  );
}