@tiptap/react 2.5.8 → 2.6.0

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,10 +1,14 @@
1
- import { EditorOptions } from '@tiptap/core'
1
+ import { type EditorOptions, Editor } 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
- import { Editor } from './Editor.js'
8
12
  import { useEditorState } from './useEditorState.js'
9
13
 
10
14
  const isDev = process.env.NODE_ENV !== 'production'
@@ -31,55 +35,69 @@ export type UseEditorOptions = Partial<EditorOptions> & {
31
35
  };
32
36
 
33
37
  /**
34
- * Create a new editor instance. And attach event listeners.
38
+ * This class handles the creation, destruction, and re-creation of the editor instance.
35
39
  */
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))
40
+ class EditorInstanceManager {
41
+ /**
42
+ * The current editor instance.
43
+ */
44
+ private editor: Editor | null = null
48
45
 
49
- return editor
50
- }
46
+ /**
47
+ * The most recent options to apply to the editor.
48
+ */
49
+ private options: MutableRefObject<UseEditorOptions>
51
50
 
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;
51
+ /**
52
+ * The subscriptions to notify when the editor instance
53
+ * has been created or destroyed.
54
+ */
55
+ private subscriptions = new Set<() => void>()
63
56
 
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;
57
+ /**
58
+ * A timeout to destroy the editor if it was not mounted within a time frame.
59
+ */
60
+ private scheduledDestructionTimeout: ReturnType<typeof setTimeout> | undefined
75
61
 
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) {
62
+ /**
63
+ * Whether the editor has been mounted.
64
+ */
65
+ private isComponentMounted = false
66
+
67
+ /**
68
+ * The most recent dependencies array.
69
+ */
70
+ private previousDeps: DependencyList | null = null
71
+
72
+ /**
73
+ * The unique instance ID. This is used to identify the editor instance. And will be re-generated for each new instance.
74
+ */
75
+ public instanceId = ''
76
+
77
+ constructor(options: MutableRefObject<UseEditorOptions>) {
78
+ this.options = options
79
+ this.subscriptions = new Set<() => void>()
80
+ this.setEditor(this.getInitialEditor())
81
+
82
+ this.getEditor = this.getEditor.bind(this)
83
+ this.getServerSnapshot = this.getServerSnapshot.bind(this)
84
+ this.subscribe = this.subscribe.bind(this)
85
+ this.refreshEditorInstance = this.refreshEditorInstance.bind(this)
86
+ this.scheduleDestroy = this.scheduleDestroy.bind(this)
87
+ this.onRender = this.onRender.bind(this)
88
+ this.createEditor = this.createEditor.bind(this)
89
+ }
90
+
91
+ private setEditor(editor: Editor | null) {
92
+ this.editor = editor
93
+ this.instanceId = Math.random().toString(36).slice(2, 9)
94
+
95
+ // Notify all subscribers that the editor instance has been created
96
+ this.subscriptions.forEach(cb => cb())
97
+ }
98
+
99
+ private getInitialEditor() {
100
+ if (this.options.current.immediatelyRender === undefined) {
83
101
  if (isSSR || isNext) {
84
102
  // TODO in the next major release, we should throw an error here
85
103
  if (isDev) {
@@ -97,70 +115,206 @@ export function useEditor(
97
115
  }
98
116
 
99
117
  // Default to immediately rendering when client-side rendering
100
- return createEditor(mostRecentOptions)
118
+ return this.createEditor()
101
119
  }
102
120
 
103
- if (options.immediatelyRender && isSSR && isDev) {
121
+ if (this.options.current.immediatelyRender && isSSR && isDev) {
104
122
  // 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
123
  throw new Error(
106
124
  '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
125
  )
108
126
  }
109
127
 
110
- if (options.immediatelyRender) {
111
- return createEditor(mostRecentOptions)
128
+ if (this.options.current.immediatelyRender) {
129
+ return this.createEditor()
112
130
  }
113
131
 
114
132
  return null
115
- })
116
- const mostRecentEditor = useRef<Editor | null>(editor)
133
+ }
117
134
 
118
- mostRecentEditor.current = editor
135
+ /**
136
+ * Create a new editor instance. And attach event listeners.
137
+ */
138
+ private createEditor(): Editor {
139
+ const optionsToApply: Partial<EditorOptions> = {
140
+ ...this.options.current,
141
+ // Always call the most recent version of the callback function by default
142
+ onBeforeCreate: (...args) => this.options.current.onBeforeCreate?.(...args),
143
+ onBlur: (...args) => this.options.current.onBlur?.(...args),
144
+ onCreate: (...args) => this.options.current.onCreate?.(...args),
145
+ onDestroy: (...args) => this.options.current.onDestroy?.(...args),
146
+ onFocus: (...args) => this.options.current.onFocus?.(...args),
147
+ onSelectionUpdate: (...args) => this.options.current.onSelectionUpdate?.(...args),
148
+ onTransaction: (...args) => this.options.current.onTransaction?.(...args),
149
+ onUpdate: (...args) => this.options.current.onUpdate?.(...args),
150
+ onContentError: (...args) => this.options.current.onContentError?.(...args),
151
+ }
152
+ const editor = new Editor(optionsToApply)
119
153
 
120
- useDebugValue(editor)
154
+ // no need to keep track of the event listeners, they will be removed when the editor is destroyed
121
155
 
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
- }
156
+ return editor
157
+ }
158
+
159
+ /**
160
+ * Get the current editor instance.
161
+ */
162
+ getEditor(): Editor | null {
163
+ return this.editor
164
+ }
165
+
166
+ /**
167
+ * Always disable the editor on the server-side.
168
+ */
169
+ getServerSnapshot(): null {
170
+ return null
171
+ }
172
+
173
+ /**
174
+ * Subscribe to the editor instance's changes.
175
+ */
176
+ subscribe(onStoreChange: () => void) {
177
+ this.subscriptions.add(onStoreChange)
178
+
179
+ return () => {
180
+ this.subscriptions.delete(onStoreChange)
137
181
  }
182
+ }
138
183
 
139
- let editorInstance = mostRecentEditor.current
184
+ /**
185
+ * On each render, we will create, update, or destroy the editor instance.
186
+ * @param deps The dependencies to watch for changes
187
+ * @returns A cleanup function
188
+ */
189
+ onRender(deps: DependencyList) {
190
+ // The returned callback will run on each render
191
+ return () => {
192
+ this.isComponentMounted = true
193
+ // Cleanup any scheduled destructions, since we are currently rendering
194
+ clearTimeout(this.scheduledDestructionTimeout)
140
195
 
141
- if (!editorInstance) {
142
- editorInstance = createEditor(mostRecentOptions)
143
- setEditor(editorInstance)
144
- return () => destroyUnusedEditor(editorInstance)
196
+ if (this.editor && !this.editor.isDestroyed && deps.length === 0) {
197
+ // if the editor does exist & deps are empty, we don't need to re-initialize the editor
198
+ // we can fast-path to update the editor options on the existing instance
199
+ this.editor.setOptions(this.options.current)
200
+ } else {
201
+ // When the editor:
202
+ // - does not yet exist
203
+ // - is destroyed
204
+ // - the deps array changes
205
+ // We need to destroy the editor instance and re-initialize it
206
+ this.refreshEditorInstance(deps)
207
+ }
208
+
209
+ return () => {
210
+ this.isComponentMounted = false
211
+ this.scheduleDestroy()
212
+ }
145
213
  }
214
+ }
215
+
216
+ /**
217
+ * Recreate the editor instance if the dependencies have changed.
218
+ */
219
+ private refreshEditorInstance(deps: DependencyList) {
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
158
255
 
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)
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
+ )
312
+
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
@@ -1,8 +1,7 @@
1
+ import type { Editor } from '@tiptap/core'
1
2
  import { useDebugValue, useEffect, useState } from 'react'
2
3
  import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector'
3
4
 
4
- import type { Editor } from './Editor.js'
5
-
6
5
  export type EditorStateSnapshot<TEditor extends Editor | null = Editor | null> = {
7
6
  editor: TEditor;
8
7
  transactionNumber: number;
@@ -30,68 +29,83 @@ export type UseEditorStateOptions<
30
29
  * To synchronize the editor instance with the component state,
31
30
  * we need to create a separate instance that is not affected by the component re-renders.
32
31
  */
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
32
+ class EditorStateManager<TEditor extends Editor | null = Editor | null> {
33
+ private transactionNumber = 0
34
+
35
+ private lastTransactionNumber = 0
36
+
37
+ private lastSnapshot: EditorStateSnapshot<TEditor>
38
+
39
+ private editor: TEditor
40
+
41
+ private subscribers = new Set<() => void>()
42
+
43
+ constructor(initialEditor: TEditor) {
44
+ this.editor = initialEditor
45
+ this.lastSnapshot = { editor: initialEditor, transactionNumber: 0 }
46
+
47
+ this.getSnapshot = this.getSnapshot.bind(this)
48
+ this.getServerSnapshot = this.getServerSnapshot.bind(this)
49
+ this.watch = this.watch.bind(this)
50
+ this.subscribe = this.subscribe.bind(this)
51
+ }
52
+
53
+ /**
54
+ * Get the current editor instance.
55
+ */
56
+ getSnapshot(): EditorStateSnapshot<TEditor> {
57
+ if (this.transactionNumber === this.lastTransactionNumber) {
58
+ return this.lastSnapshot
59
+ }
60
+ this.lastTransactionNumber = this.transactionNumber
61
+ this.lastSnapshot = { editor: this.editor, transactionNumber: this.transactionNumber }
62
+ return this.lastSnapshot
63
+ }
64
+
65
+ /**
66
+ * Always disable the editor on the server-side.
67
+ */
68
+ getServerSnapshot(): EditorStateSnapshot<null> {
69
+ return { editor: null, transactionNumber: 0 }
70
+ }
71
+
72
+ /**
73
+ * Subscribe to the editor instance's changes.
74
+ */
75
+ subscribe(callback: () => void): () => void {
76
+ this.subscribers.add(callback)
77
+ return () => {
78
+ this.subscribers.delete(callback)
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Watch the editor instance for changes.
84
+ */
85
+ watch(nextEditor: Editor | null): undefined | (() => void) {
86
+ this.editor = nextEditor as TEditor
87
+
88
+ if (this.editor) {
89
+ /**
90
+ * This will force a re-render when the editor state changes.
91
+ * This is to support things like `editor.can().toggleBold()` in components that `useEditor`.
92
+ * This could be more efficient, but it's a good trade-off for now.
93
+ */
94
+ const fn = () => {
95
+ this.transactionNumber += 1
96
+ this.subscribers.forEach(callback => callback())
47
97
  }
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)
98
+
99
+ const currentEditor = this.editor
100
+
101
+ currentEditor.on('transaction', fn)
63
102
  return () => {
64
- subscribers.delete(callback)
103
+ currentEditor.off('transaction', fn)
65
104
  }
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
- }
105
+ }
93
106
 
94
- return editorInstance
107
+ return undefined
108
+ }
95
109
  }
96
110
 
97
111
  export function useEditorState<TSelectorResult>(
@@ -104,7 +118,7 @@ export function useEditorState<TSelectorResult>(
104
118
  export function useEditorState<TSelectorResult>(
105
119
  options: UseEditorStateOptions<TSelectorResult, Editor> | UseEditorStateOptions<TSelectorResult, Editor | null>,
106
120
  ): TSelectorResult | null {
107
- const [editorInstance] = useState(() => makeEditorStateInstance(options.editor))
121
+ const [editorInstance] = useState(() => new EditorStateManager(options.editor))
108
122
 
109
123
  // Using the `useSyncExternalStore` hook to sync the editor instance with the component state
110
124
  const selectedState = useSyncExternalStoreWithSelector(
@@ -117,7 +131,7 @@ export function useEditorState<TSelectorResult>(
117
131
 
118
132
  useEffect(() => {
119
133
  return editorInstance.watch(options.editor)
120
- }, [options.editor])
134
+ }, [options.editor, editorInstance])
121
135
 
122
136
  useDebugValue(selectedState)
123
137