@tiptap/react 2.5.8 → 2.5.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/useEditor.ts CHANGED
@@ -1,8 +1,13 @@
1
1
  import { EditorOptions } from '@tiptap/core'
2
2
  import {
3
- DependencyList, MutableRefObject,
4
- useDebugValue, useEffect, useRef, useState,
3
+ DependencyList,
4
+ MutableRefObject,
5
+ useDebugValue,
6
+ useEffect,
7
+ useRef,
8
+ useState,
5
9
  } from 'react'
10
+ import { useSyncExternalStore } from 'use-sync-external-store/shim'
6
11
 
7
12
  import { Editor } from './Editor.js'
8
13
  import { useEditorState } from './useEditorState.js'
@@ -31,55 +36,69 @@ export type UseEditorOptions = Partial<EditorOptions> & {
31
36
  };
32
37
 
33
38
  /**
34
- * Create a new editor instance. And attach event listeners.
39
+ * This class handles the creation, destruction, and re-creation of the editor instance.
35
40
  */
36
- function createEditor(options: MutableRefObject<UseEditorOptions>): Editor {
37
- const editor = new Editor(options.current)
38
-
39
- editor.on('beforeCreate', (...args) => options.current.onBeforeCreate?.(...args))
40
- editor.on('blur', (...args) => options.current.onBlur?.(...args))
41
- editor.on('create', (...args) => options.current.onCreate?.(...args))
42
- editor.on('destroy', (...args) => options.current.onDestroy?.(...args))
43
- editor.on('focus', (...args) => options.current.onFocus?.(...args))
44
- editor.on('selectionUpdate', (...args) => options.current.onSelectionUpdate?.(...args))
45
- editor.on('transaction', (...args) => options.current.onTransaction?.(...args))
46
- editor.on('update', (...args) => options.current.onUpdate?.(...args))
47
- editor.on('contentError', (...args) => options.current.onContentError?.(...args))
41
+ class EditorInstanceManager {
42
+ /**
43
+ * The current editor instance.
44
+ */
45
+ private editor: Editor | null = null
48
46
 
49
- return editor
50
- }
47
+ /**
48
+ * The most recent options to apply to the editor.
49
+ */
50
+ private options: MutableRefObject<UseEditorOptions>
51
51
 
52
- /**
53
- * This hook allows you to create an editor instance.
54
- * @param options The editor options
55
- * @param deps The dependencies to watch for changes
56
- * @returns The editor instance
57
- * @example const editor = useEditor({ extensions: [...] })
58
- */
59
- export function useEditor(
60
- options: UseEditorOptions & { immediatelyRender: true },
61
- deps?: DependencyList
62
- ): Editor;
52
+ /**
53
+ * The subscriptions to notify when the editor instance
54
+ * has been created or destroyed.
55
+ */
56
+ private subscriptions = new Set<() => void>()
63
57
 
64
- /**
65
- * This hook allows you to create an editor instance.
66
- * @param options The editor options
67
- * @param deps The dependencies to watch for changes
68
- * @returns The editor instance
69
- * @example const editor = useEditor({ extensions: [...] })
70
- */
71
- export function useEditor(
72
- options?: UseEditorOptions,
73
- deps?: DependencyList
74
- ): Editor | null;
58
+ /**
59
+ * A timeout to destroy the editor if it was not mounted within a time frame.
60
+ */
61
+ private scheduledDestructionTimeout: ReturnType<typeof setTimeout> | undefined
75
62
 
76
- export function useEditor(
77
- options: UseEditorOptions = {},
78
- deps: DependencyList = [],
79
- ): Editor | null {
80
- const mostRecentOptions = useRef(options)
81
- const [editor, setEditor] = useState(() => {
82
- if (options.immediatelyRender === undefined) {
63
+ /**
64
+ * Whether the editor has been mounted.
65
+ */
66
+ private isComponentMounted = false
67
+
68
+ /**
69
+ * The most recent dependencies array.
70
+ */
71
+ private previousDeps: DependencyList | null = null
72
+
73
+ /**
74
+ * The unique instance ID. This is used to identify the editor instance. And will be re-generated for each new instance.
75
+ */
76
+ public instanceId = ''
77
+
78
+ constructor(options: MutableRefObject<UseEditorOptions>) {
79
+ this.options = options
80
+ this.subscriptions = new Set<() => void>()
81
+ this.setEditor(this.getInitialEditor())
82
+
83
+ this.getEditor = this.getEditor.bind(this)
84
+ this.getServerSnapshot = this.getServerSnapshot.bind(this)
85
+ this.subscribe = this.subscribe.bind(this)
86
+ this.refreshEditorInstance = this.refreshEditorInstance.bind(this)
87
+ this.scheduleDestroy = this.scheduleDestroy.bind(this)
88
+ this.onRender = this.onRender.bind(this)
89
+ this.createEditor = this.createEditor.bind(this)
90
+ }
91
+
92
+ private setEditor(editor: Editor | null) {
93
+ this.editor = editor
94
+ this.instanceId = Math.random().toString(36).slice(2, 9)
95
+
96
+ // Notify all subscribers that the editor instance has been created
97
+ this.subscriptions.forEach(cb => cb())
98
+ }
99
+
100
+ private getInitialEditor() {
101
+ if (this.options.current.immediatelyRender === undefined) {
83
102
  if (isSSR || isNext) {
84
103
  // TODO in the next major release, we should throw an error here
85
104
  if (isDev) {
@@ -97,70 +116,205 @@ export function useEditor(
97
116
  }
98
117
 
99
118
  // Default to immediately rendering when client-side rendering
100
- return createEditor(mostRecentOptions)
119
+ return this.createEditor()
101
120
  }
102
121
 
103
- if (options.immediatelyRender && isSSR && isDev) {
122
+ if (this.options.current.immediatelyRender && isSSR && isDev) {
104
123
  // Warn in development, to make sure the developer is aware that tiptap cannot be SSR'd, set `immediatelyRender` to `false` to avoid hydration mismatches.
105
124
  throw new Error(
106
125
  'Tiptap Error: SSR has been detected, and `immediatelyRender` has been set to `true` this is an unsupported configuration that may result in errors, explicitly set `immediatelyRender` to `false` to avoid hydration mismatches.',
107
126
  )
108
127
  }
109
128
 
110
- if (options.immediatelyRender) {
111
- return createEditor(mostRecentOptions)
129
+ if (this.options.current.immediatelyRender) {
130
+ return this.createEditor()
112
131
  }
113
132
 
114
133
  return null
115
- })
116
- const mostRecentEditor = useRef<Editor | null>(editor)
134
+ }
117
135
 
118
- mostRecentEditor.current = editor
136
+ /**
137
+ * Create a new editor instance. And attach event listeners.
138
+ */
139
+ private createEditor(): Editor {
140
+ const editor = new Editor(this.options.current)
119
141
 
120
- useDebugValue(editor)
142
+ // Always call the most recent version of the callback function by default
143
+ editor.on('beforeCreate', (...args) => this.options.current.onBeforeCreate?.(...args))
144
+ editor.on('blur', (...args) => this.options.current.onBlur?.(...args))
145
+ editor.on('create', (...args) => this.options.current.onCreate?.(...args))
146
+ editor.on('destroy', (...args) => this.options.current.onDestroy?.(...args))
147
+ editor.on('focus', (...args) => this.options.current.onFocus?.(...args))
148
+ editor.on('selectionUpdate', (...args) => this.options.current.onSelectionUpdate?.(...args))
149
+ editor.on('transaction', (...args) => this.options.current.onTransaction?.(...args))
150
+ editor.on('update', (...args) => this.options.current.onUpdate?.(...args))
151
+ editor.on('contentError', (...args) => this.options.current.onContentError?.(...args))
121
152
 
122
- // This effect will handle creating/updating the editor instance
123
- useEffect(() => {
124
- const destroyUnusedEditor = (editorInstance: Editor | null) => {
125
- if (editorInstance) {
126
- // We need to destroy the editor asynchronously to avoid memory leaks
127
- // because the editor instance is still being used in the component.
128
-
129
- setTimeout(() => {
130
- // re-use the editor instance if it hasn't been replaced yet
131
- // otherwise, asynchronously destroy the old editor instance
132
- if (editorInstance !== mostRecentEditor.current && !editorInstance.isDestroyed) {
133
- editorInstance.destroy()
134
- }
135
- })
136
- }
153
+ // no need to keep track of the event listeners, they will be removed when the editor is destroyed
154
+
155
+ return editor
156
+ }
157
+
158
+ /**
159
+ * Get the current editor instance.
160
+ */
161
+ getEditor(): Editor | null {
162
+ return this.editor
163
+ }
164
+
165
+ /**
166
+ * Always disable the editor on the server-side.
167
+ */
168
+ getServerSnapshot(): null {
169
+ return null
170
+ }
171
+
172
+ /**
173
+ * Subscribe to the editor instance's changes.
174
+ */
175
+ subscribe(onStoreChange: () => void) {
176
+ this.subscriptions.add(onStoreChange)
177
+
178
+ return () => {
179
+ this.subscriptions.delete(onStoreChange)
137
180
  }
181
+ }
138
182
 
139
- let editorInstance = mostRecentEditor.current
183
+ /**
184
+ * On each render, we will create, update, or destroy the editor instance.
185
+ * @param deps The dependencies to watch for changes
186
+ * @returns A cleanup function
187
+ */
188
+ onRender(deps: DependencyList) {
189
+ // The returned callback will run on each render
190
+ return () => {
191
+ this.isComponentMounted = true
192
+ // Cleanup any scheduled destructions, since we are currently rendering
193
+ clearTimeout(this.scheduledDestructionTimeout)
140
194
 
141
- if (!editorInstance) {
142
- editorInstance = createEditor(mostRecentOptions)
143
- setEditor(editorInstance)
144
- return () => destroyUnusedEditor(editorInstance)
195
+ if (this.editor && !this.editor.isDestroyed && deps.length === 0) {
196
+ // if the editor does exist & deps are empty, we don't need to re-initialize the editor
197
+ // we can fast-path to update the editor options on the existing instance
198
+ this.editor.setOptions(this.options.current)
199
+ } else {
200
+ // When the editor:
201
+ // - does not yet exist
202
+ // - is destroyed
203
+ // - the deps array changes
204
+ // We need to destroy the editor instance and re-initialize it
205
+ this.refreshEditorInstance(deps)
206
+ }
207
+
208
+ return () => {
209
+ this.isComponentMounted = false
210
+ this.scheduleDestroy()
211
+ }
145
212
  }
213
+ }
214
+
215
+ /**
216
+ * Recreate the editor instance if the dependencies have changed.
217
+ */
218
+ private refreshEditorInstance(deps: DependencyList) {
219
+
220
+ if (this.editor && !this.editor.isDestroyed) {
221
+ // Editor instance already exists
222
+ if (this.previousDeps === null) {
223
+ // If lastDeps has not yet been initialized, reuse the current editor instance
224
+ this.previousDeps = deps
225
+ return
226
+ }
227
+ const depsAreEqual = this.previousDeps.length === deps.length
228
+ && this.previousDeps.every((dep, index) => dep === deps[index])
146
229
 
147
- if (!Array.isArray(deps) || deps.length === 0) {
148
- // if the editor does exist & deps are empty, we don't need to re-initialize the editor
149
- // we can fast-path to update the editor options on the existing instance
150
- editorInstance.setOptions(options)
230
+ if (depsAreEqual) {
231
+ // deps exist and are equal, no need to recreate
232
+ return
233
+ }
234
+ }
151
235
 
152
- return () => destroyUnusedEditor(editorInstance)
236
+ if (this.editor && !this.editor.isDestroyed) {
237
+ // Destroy the editor instance if it exists
238
+ this.editor.destroy()
153
239
  }
154
240
 
155
- // We need to destroy the editor instance and re-initialize it
156
- // when the deps array changes
157
- editorInstance.destroy()
241
+ this.setEditor(this.createEditor())
242
+
243
+ // Update the lastDeps to the current deps
244
+ this.previousDeps = deps
245
+ }
246
+
247
+ /**
248
+ * Schedule the destruction of the editor instance.
249
+ * This will only destroy the editor if it was not mounted on the next tick.
250
+ * This is to avoid destroying the editor instance when it's actually still mounted.
251
+ */
252
+ private scheduleDestroy() {
253
+ const currentInstanceId = this.instanceId
254
+ const currentEditor = this.editor
255
+
256
+ // Wait a tick to see if the component is still mounted
257
+ this.scheduledDestructionTimeout = setTimeout(() => {
258
+ if (this.isComponentMounted && this.instanceId === currentInstanceId) {
259
+ // If still mounted on the next tick, with the same instanceId, do not destroy the editor
260
+ if (currentEditor) {
261
+ // just re-apply options as they might have changed
262
+ currentEditor.setOptions(this.options.current)
263
+ }
264
+ return
265
+ }
266
+ if (currentEditor && !currentEditor.isDestroyed) {
267
+ currentEditor.destroy()
268
+ if (this.instanceId === currentInstanceId) {
269
+ this.setEditor(null)
270
+ }
271
+ }
272
+ }, 0)
273
+ }
274
+ }
275
+
276
+ /**
277
+ * This hook allows you to create an editor instance.
278
+ * @param options The editor options
279
+ * @param deps The dependencies to watch for changes
280
+ * @returns The editor instance
281
+ * @example const editor = useEditor({ extensions: [...] })
282
+ */
283
+ export function useEditor(
284
+ options: UseEditorOptions & { immediatelyRender: true },
285
+ deps?: DependencyList
286
+ ): Editor;
287
+
288
+ /**
289
+ * This hook allows you to create an editor instance.
290
+ * @param options The editor options
291
+ * @param deps The dependencies to watch for changes
292
+ * @returns The editor instance
293
+ * @example const editor = useEditor({ extensions: [...] })
294
+ */
295
+ export function useEditor(options?: UseEditorOptions, deps?: DependencyList): Editor | null;
296
+
297
+ export function useEditor(
298
+ options: UseEditorOptions = {},
299
+ deps: DependencyList = [],
300
+ ): Editor | null {
301
+ const mostRecentOptions = useRef(options)
302
+
303
+ mostRecentOptions.current = options
304
+
305
+ const [instanceManager] = useState(() => new EditorInstanceManager(mostRecentOptions))
306
+
307
+ const editor = useSyncExternalStore(
308
+ instanceManager.subscribe,
309
+ instanceManager.getEditor,
310
+ instanceManager.getServerSnapshot,
311
+ )
158
312
 
159
- // the deps array is used to re-initialize the editor instance
160
- editorInstance = createEditor(mostRecentOptions)
161
- setEditor(editorInstance)
162
- return () => destroyUnusedEditor(editorInstance)
163
- }, deps)
313
+ useDebugValue(editor)
314
+
315
+ // This effect will handle creating/updating the editor instance
316
+ // eslint-disable-next-line react-hooks/exhaustive-deps
317
+ useEffect(instanceManager.onRender(deps))
164
318
 
165
319
  // The default behavior is to re-render on each transaction
166
320
  // This is legacy behavior that will be removed in future versions
@@ -30,68 +30,83 @@ export type UseEditorStateOptions<
30
30
  * To synchronize the editor instance with the component state,
31
31
  * we need to create a separate instance that is not affected by the component re-renders.
32
32
  */
33
- function makeEditorStateInstance<TEditor extends Editor | null = Editor | null>(initialEditor: TEditor) {
34
- let transactionNumber = 0
35
- let lastTransactionNumber = 0
36
- let lastSnapshot: EditorStateSnapshot<TEditor> = { editor: initialEditor, transactionNumber: 0 }
37
- let editor = initialEditor
38
- const subscribers = new Set<() => void>()
39
-
40
- const editorInstance = {
41
- /**
42
- * Get the current editor instance.
43
- */
44
- getSnapshot(): EditorStateSnapshot<TEditor> {
45
- if (transactionNumber === lastTransactionNumber) {
46
- return lastSnapshot
33
+ class EditorStateManager<TEditor extends Editor | null = Editor | null> {
34
+ private transactionNumber = 0
35
+
36
+ private lastTransactionNumber = 0
37
+
38
+ private lastSnapshot: EditorStateSnapshot<TEditor>
39
+
40
+ private editor: TEditor
41
+
42
+ private subscribers = new Set<() => void>()
43
+
44
+ constructor(initialEditor: TEditor) {
45
+ this.editor = initialEditor
46
+ this.lastSnapshot = { editor: initialEditor, transactionNumber: 0 }
47
+
48
+ this.getSnapshot = this.getSnapshot.bind(this)
49
+ this.getServerSnapshot = this.getServerSnapshot.bind(this)
50
+ this.watch = this.watch.bind(this)
51
+ this.subscribe = this.subscribe.bind(this)
52
+ }
53
+
54
+ /**
55
+ * Get the current editor instance.
56
+ */
57
+ getSnapshot(): EditorStateSnapshot<TEditor> {
58
+ if (this.transactionNumber === this.lastTransactionNumber) {
59
+ return this.lastSnapshot
60
+ }
61
+ this.lastTransactionNumber = this.transactionNumber
62
+ this.lastSnapshot = { editor: this.editor, transactionNumber: this.transactionNumber }
63
+ return this.lastSnapshot
64
+ }
65
+
66
+ /**
67
+ * Always disable the editor on the server-side.
68
+ */
69
+ getServerSnapshot(): EditorStateSnapshot<null> {
70
+ return { editor: null, transactionNumber: 0 }
71
+ }
72
+
73
+ /**
74
+ * Subscribe to the editor instance's changes.
75
+ */
76
+ subscribe(callback: () => void): () => void {
77
+ this.subscribers.add(callback)
78
+ return () => {
79
+ this.subscribers.delete(callback)
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Watch the editor instance for changes.
85
+ */
86
+ watch(nextEditor: Editor | null): undefined | (() => void) {
87
+ this.editor = nextEditor as TEditor
88
+
89
+ if (this.editor) {
90
+ /**
91
+ * This will force a re-render when the editor state changes.
92
+ * This is to support things like `editor.can().toggleBold()` in components that `useEditor`.
93
+ * This could be more efficient, but it's a good trade-off for now.
94
+ */
95
+ const fn = () => {
96
+ this.transactionNumber += 1
97
+ this.subscribers.forEach(callback => callback())
47
98
  }
48
- lastTransactionNumber = transactionNumber
49
- lastSnapshot = { editor, transactionNumber }
50
- return lastSnapshot
51
- },
52
- /**
53
- * Always disable the editor on the server-side.
54
- */
55
- getServerSnapshot(): EditorStateSnapshot<null> {
56
- return { editor: null, transactionNumber: 0 }
57
- },
58
- /**
59
- * Subscribe to the editor instance's changes.
60
- */
61
- subscribe(callback: () => void) {
62
- subscribers.add(callback)
99
+
100
+ const currentEditor = this.editor
101
+
102
+ currentEditor.on('transaction', fn)
63
103
  return () => {
64
- subscribers.delete(callback)
104
+ currentEditor.off('transaction', fn)
65
105
  }
66
- },
67
- /**
68
- * Watch the editor instance for changes.
69
- */
70
- watch(nextEditor: Editor | null) {
71
- editor = nextEditor as TEditor
72
-
73
- if (editor) {
74
- /**
75
- * This will force a re-render when the editor state changes.
76
- * This is to support things like `editor.can().toggleBold()` in components that `useEditor`.
77
- * This could be more efficient, but it's a good trade-off for now.
78
- */
79
- const fn = () => {
80
- transactionNumber += 1
81
- subscribers.forEach(callback => callback())
82
- }
83
-
84
- const currentEditor = editor
85
-
86
- currentEditor.on('transaction', fn)
87
- return () => {
88
- currentEditor.off('transaction', fn)
89
- }
90
- }
91
- },
92
- }
106
+ }
93
107
 
94
- return editorInstance
108
+ return undefined
109
+ }
95
110
  }
96
111
 
97
112
  export function useEditorState<TSelectorResult>(
@@ -104,7 +119,7 @@ export function useEditorState<TSelectorResult>(
104
119
  export function useEditorState<TSelectorResult>(
105
120
  options: UseEditorStateOptions<TSelectorResult, Editor> | UseEditorStateOptions<TSelectorResult, Editor | null>,
106
121
  ): TSelectorResult | null {
107
- const [editorInstance] = useState(() => makeEditorStateInstance(options.editor))
122
+ const [editorInstance] = useState(() => new EditorStateManager(options.editor))
108
123
 
109
124
  // Using the `useSyncExternalStore` hook to sync the editor instance with the component state
110
125
  const selectedState = useSyncExternalStoreWithSelector(
@@ -117,7 +132,7 @@ export function useEditorState<TSelectorResult>(
117
132
 
118
133
  useEffect(() => {
119
134
  return editorInstance.watch(options.editor)
120
- }, [options.editor])
135
+ }, [options.editor, editorInstance])
121
136
 
122
137
  useDebugValue(selectedState)
123
138