File size: 1,963 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
'use client'

import { Component, createRef, type ReactNode } from 'react'

interface ErrorBoundaryProps {
  children: ReactNode
}

interface ErrorBoundaryState {
  hasError: boolean
}

function getDomNodeAttributes(node: HTMLElement): Record<string, string> {
  const result: Record<string, string> = {}
  for (let i = 0; i < node.attributes.length; i++) {
    const attr = node.attributes[i]
    result[attr.name] = attr.value
  }
  return result
}

export class GracefulDegradeBoundary extends Component<
  ErrorBoundaryProps,
  ErrorBoundaryState
> {
  private rootHtml: string
  private htmlAttributes: Record<string, string>
  private htmlRef: React.RefObject<HTMLHtmlElement | null>

  constructor(props: ErrorBoundaryProps) {
    super(props)
    this.state = { hasError: false }
    this.rootHtml = ''
    this.htmlAttributes = {}
    this.htmlRef = createRef<HTMLHtmlElement>()
  }

  static getDerivedStateFromError(_: unknown): ErrorBoundaryState {
    return { hasError: true }
  }

  componentDidMount() {
    const htmlNode = this.htmlRef.current
    if (this.state.hasError && htmlNode) {
      // Reapply the cached HTML attributes to the root element
      Object.entries(this.htmlAttributes).forEach(([key, value]) => {
        htmlNode.setAttribute(key, value)
      })
    }
  }

  render() {
    const { hasError } = this.state
    // Cache the root HTML content on the first render
    if (typeof window !== 'undefined' && !this.rootHtml) {
      this.rootHtml = document.documentElement.innerHTML
      this.htmlAttributes = getDomNodeAttributes(document.documentElement)
    }

    if (hasError) {
      // Render the current HTML content without hydration
      return (
        <html
          ref={this.htmlRef}
          suppressHydrationWarning
          dangerouslySetInnerHTML={{
            __html: this.rootHtml,
          }}
        />
      )
    }

    return this.props.children
  }
}

export default GracefulDegradeBoundary