File size: 5,514 Bytes
2daf8de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import type { Editor } from '@tiptap/core'
import type { ForwardedRef, HTMLProps, LegacyRef, MutableRefObject } from 'react'
import React, { forwardRef } from 'react'
import ReactDOM from 'react-dom'
import { useSyncExternalStore } from 'use-sync-external-store/shim/index.js'

import type { ContentComponent, EditorWithContentComponent } from './Editor.js'
import type { ReactRenderer } from './ReactRenderer.js'

const mergeRefs = <T extends HTMLDivElement>(
  ...refs: Array<MutableRefObject<T> | LegacyRef<T> | undefined>
) => {
  return (node: T) => {
    refs.forEach(ref => {
      if (typeof ref === 'function') {
        ref(node)
      } else if (ref) {
        ;(ref as MutableRefObject<T | null>).current = node
      }
    })
  }
}

/**
 * This component renders all of the editor's node views.
 */
const Portals: React.FC<{ contentComponent: ContentComponent }> = ({ contentComponent }) => {
  // For performance reasons, we render the node view portals on state changes only
  const renderers = useSyncExternalStore(
    contentComponent.subscribe,
    contentComponent.getSnapshot,
    contentComponent.getServerSnapshot,
  )

  // This allows us to directly render the portals without any additional wrapper
  return <>{Object.values(renderers)}</>
}

export interface EditorContentProps extends HTMLProps<HTMLDivElement> {
  editor: Editor | null
  innerRef?: ForwardedRef<HTMLDivElement | null>
}

export function createContentComponent(): ContentComponent {
  const subscribers = new Set<() => void>()
  let renderers: Record<string, React.ReactPortal> = {}
  let isNotificationQueued = false

  const notifySubscribers = () => {
    if (isNotificationQueued || !subscribers.size) {
      return
    }

    isNotificationQueued = true

    queueMicrotask(() => {
      isNotificationQueued = false
      subscribers.forEach(subscriber => subscriber())
    })
  }

  return {
    /**
     * Subscribe to the editor instance's changes.
     */
    subscribe(callback: () => void) {
      subscribers.add(callback)
      return () => {
        subscribers.delete(callback)
      }
    },
    getSnapshot() {
      return renderers
    },
    getServerSnapshot() {
      return renderers
    },
    /**
     * Adds a new NodeView Renderer to the editor.
     */
    setRenderer(id: string, renderer: ReactRenderer) {
      renderers = {
        ...renderers,
        [id]: ReactDOM.createPortal(renderer.reactElement, renderer.element, id),
      }

      notifySubscribers()
    },
    /**
     * Removes a NodeView Renderer from the editor.
     */
    removeRenderer(id: string) {
      const nextRenderers = { ...renderers }

      delete nextRenderers[id]
      renderers = nextRenderers
      notifySubscribers()
    },
  }
}

export class PureEditorContent extends React.Component<
  EditorContentProps,
  { hasContentComponentInitialized: boolean }
> {
  editorContentRef: React.RefObject<any>

  constructor(props: EditorContentProps) {
    super(props)
    this.editorContentRef = React.createRef()
  }

  componentDidMount() {
    this.init()
  }

  componentDidUpdate() {
    this.init()
  }

  init() {
    const editor = this.props.editor as EditorWithContentComponent | null

    if (editor && !editor.isDestroyed && editor.view.dom?.parentNode) {
      if (editor.contentComponent) {
        return
      }

      const element = this.editorContentRef.current

      element.append(...editor.view.dom.parentNode.childNodes)

      editor.setOptions({
        element,
      })

      editor.contentComponent = createContentComponent()

      editor.createNodeViews()

      editor.isEditorContentInitialized = true

      this.forceUpdate()
    }
  }

  componentWillUnmount() {
    const editor = this.props.editor as EditorWithContentComponent | null

    if (!editor) {
      return
    }

    editor.isEditorContentInitialized = false

    if (!editor.isDestroyed) {
      editor.view.setProps({
        nodeViews: {},
      })
    }

    editor.contentComponent = null

    // try to reset the editor element
    // may fail if this editor's view.dom was never initialized/mounted yet
    try {
      if (!editor.view.dom?.parentNode) {
        return
      }

      // TODO using the new editor.mount method might allow us to remove this
      const newElement = document.createElement('div')

      newElement.append(...editor.view.dom.parentNode.childNodes)

      editor.setOptions({
        element: newElement,
      })
    } catch {
      // do nothing, nothing to reset
    }
  }

  render() {
    const { editor, innerRef, ...rest } = this.props

    return (
      <>
        <div ref={mergeRefs(innerRef, this.editorContentRef)} {...rest} />
        {/* @ts-ignore */}
        {editor?.contentComponent && <Portals contentComponent={editor.contentComponent} />}
      </>
    )
  }
}

// EditorContent should be re-created whenever the Editor instance changes
const EditorContentWithKey = forwardRef<HTMLDivElement, EditorContentProps>(
  (props: Omit<EditorContentProps, 'innerRef'>, ref) => {
    const key = React.useMemo(() => {
      return Math.floor(Math.random() * 0xffffffff).toString()
      // oxlint-disable-next-line react-hooks/exhaustive-deps
    }, [props.editor])

    // Can't use JSX here because it conflicts with the type definition of Vue's JSX, so use createElement
    return React.createElement(PureEditorContent, {
      key,
      innerRef: ref,
      ...props,
    })
  },
)

export const EditorContent = React.memo(EditorContentWithKey)