@tiptap/react 3.0.0-next.0 → 3.0.0-next.1

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.
Files changed (199) hide show
  1. package/dist/index.cjs +871 -1126
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +221 -0
  4. package/dist/index.d.ts +221 -0
  5. package/dist/index.js +828 -1097
  6. package/dist/index.js.map +1 -1
  7. package/package.json +10 -12
  8. package/src/Context.tsx +1 -1
  9. package/src/Editor.ts +7 -8
  10. package/src/EditorContent.tsx +98 -50
  11. package/src/NodeViewContent.tsx +1 -0
  12. package/src/NodeViewWrapper.tsx +1 -0
  13. package/src/ReactNodeViewRenderer.tsx +17 -18
  14. package/src/ReactRenderer.tsx +19 -7
  15. package/src/index.ts +0 -1
  16. package/src/useEditor.ts +244 -91
  17. package/src/useEditorState.ts +76 -62
  18. package/dist/index.umd.js +0 -1176
  19. package/dist/index.umd.js.map +0 -1
  20. package/dist/packages/core/src/CommandManager.d.ts +0 -20
  21. package/dist/packages/core/src/Editor.d.ts +0 -159
  22. package/dist/packages/core/src/EventEmitter.d.ts +0 -11
  23. package/dist/packages/core/src/Extension.d.ts +0 -343
  24. package/dist/packages/core/src/ExtensionManager.d.ts +0 -55
  25. package/dist/packages/core/src/InputRule.d.ts +0 -42
  26. package/dist/packages/core/src/Mark.d.ts +0 -451
  27. package/dist/packages/core/src/Node.d.ts +0 -611
  28. package/dist/packages/core/src/NodePos.d.ts +0 -44
  29. package/dist/packages/core/src/NodeView.d.ts +0 -31
  30. package/dist/packages/core/src/PasteRule.d.ts +0 -50
  31. package/dist/packages/core/src/Tracker.d.ts +0 -11
  32. package/dist/packages/core/src/commands/blur.d.ts +0 -13
  33. package/dist/packages/core/src/commands/clearContent.d.ts +0 -14
  34. package/dist/packages/core/src/commands/clearNodes.d.ts +0 -13
  35. package/dist/packages/core/src/commands/command.d.ts +0 -18
  36. package/dist/packages/core/src/commands/createParagraphNear.d.ts +0 -13
  37. package/dist/packages/core/src/commands/cut.d.ts +0 -20
  38. package/dist/packages/core/src/commands/deleteCurrentNode.d.ts +0 -13
  39. package/dist/packages/core/src/commands/deleteNode.d.ts +0 -15
  40. package/dist/packages/core/src/commands/deleteRange.d.ts +0 -14
  41. package/dist/packages/core/src/commands/deleteSelection.d.ts +0 -13
  42. package/dist/packages/core/src/commands/enter.d.ts +0 -13
  43. package/dist/packages/core/src/commands/exitCode.d.ts +0 -13
  44. package/dist/packages/core/src/commands/extendMarkRange.d.ts +0 -25
  45. package/dist/packages/core/src/commands/first.d.ts +0 -14
  46. package/dist/packages/core/src/commands/focus.d.ts +0 -27
  47. package/dist/packages/core/src/commands/forEach.d.ts +0 -14
  48. package/dist/packages/core/src/commands/index.d.ts +0 -55
  49. package/dist/packages/core/src/commands/insertContent.d.ts +0 -34
  50. package/dist/packages/core/src/commands/insertContentAt.d.ts +0 -47
  51. package/dist/packages/core/src/commands/join.d.ts +0 -41
  52. package/dist/packages/core/src/commands/joinItemBackward.d.ts +0 -13
  53. package/dist/packages/core/src/commands/joinItemForward.d.ts +0 -13
  54. package/dist/packages/core/src/commands/joinTextblockBackward.d.ts +0 -12
  55. package/dist/packages/core/src/commands/joinTextblockForward.d.ts +0 -12
  56. package/dist/packages/core/src/commands/keyboardShortcut.d.ts +0 -14
  57. package/dist/packages/core/src/commands/lift.d.ts +0 -17
  58. package/dist/packages/core/src/commands/liftEmptyBlock.d.ts +0 -13
  59. package/dist/packages/core/src/commands/liftListItem.d.ts +0 -15
  60. package/dist/packages/core/src/commands/newlineInCode.d.ts +0 -13
  61. package/dist/packages/core/src/commands/resetAttributes.d.ts +0 -16
  62. package/dist/packages/core/src/commands/scrollIntoView.d.ts +0 -13
  63. package/dist/packages/core/src/commands/selectAll.d.ts +0 -13
  64. package/dist/packages/core/src/commands/selectNodeBackward.d.ts +0 -13
  65. package/dist/packages/core/src/commands/selectNodeForward.d.ts +0 -13
  66. package/dist/packages/core/src/commands/selectParentNode.d.ts +0 -13
  67. package/dist/packages/core/src/commands/selectTextblockEnd.d.ts +0 -13
  68. package/dist/packages/core/src/commands/selectTextblockStart.d.ts +0 -13
  69. package/dist/packages/core/src/commands/setContent.d.ts +0 -40
  70. package/dist/packages/core/src/commands/setMark.d.ts +0 -15
  71. package/dist/packages/core/src/commands/setMeta.d.ts +0 -15
  72. package/dist/packages/core/src/commands/setNode.d.ts +0 -16
  73. package/dist/packages/core/src/commands/setNodeSelection.d.ts +0 -14
  74. package/dist/packages/core/src/commands/setTextSelection.d.ts +0 -14
  75. package/dist/packages/core/src/commands/sinkListItem.d.ts +0 -15
  76. package/dist/packages/core/src/commands/splitBlock.d.ts +0 -17
  77. package/dist/packages/core/src/commands/splitListItem.d.ts +0 -15
  78. package/dist/packages/core/src/commands/toggleList.d.ts +0 -18
  79. package/dist/packages/core/src/commands/toggleMark.d.ts +0 -30
  80. package/dist/packages/core/src/commands/toggleNode.d.ts +0 -17
  81. package/dist/packages/core/src/commands/toggleWrap.d.ts +0 -16
  82. package/dist/packages/core/src/commands/undoInputRule.d.ts +0 -13
  83. package/dist/packages/core/src/commands/unsetAllMarks.d.ts +0 -13
  84. package/dist/packages/core/src/commands/unsetMark.d.ts +0 -25
  85. package/dist/packages/core/src/commands/updateAttributes.d.ts +0 -24
  86. package/dist/packages/core/src/commands/wrapIn.d.ts +0 -16
  87. package/dist/packages/core/src/commands/wrapInList.d.ts +0 -16
  88. package/dist/packages/core/src/extensions/clipboardTextSerializer.d.ts +0 -5
  89. package/dist/packages/core/src/extensions/commands.d.ts +0 -3
  90. package/dist/packages/core/src/extensions/editable.d.ts +0 -2
  91. package/dist/packages/core/src/extensions/focusEvents.d.ts +0 -2
  92. package/dist/packages/core/src/extensions/index.d.ts +0 -6
  93. package/dist/packages/core/src/extensions/keymap.d.ts +0 -2
  94. package/dist/packages/core/src/extensions/tabindex.d.ts +0 -2
  95. package/dist/packages/core/src/helpers/combineTransactionSteps.d.ts +0 -10
  96. package/dist/packages/core/src/helpers/createChainableState.d.ts +0 -10
  97. package/dist/packages/core/src/helpers/createDocument.d.ts +0 -12
  98. package/dist/packages/core/src/helpers/createNodeFromContent.d.ts +0 -15
  99. package/dist/packages/core/src/helpers/defaultBlockAt.d.ts +0 -7
  100. package/dist/packages/core/src/helpers/findChildren.d.ts +0 -9
  101. package/dist/packages/core/src/helpers/findChildrenInRange.d.ts +0 -10
  102. package/dist/packages/core/src/helpers/findParentNode.d.ts +0 -16
  103. package/dist/packages/core/src/helpers/findParentNodeClosestToPos.d.ts +0 -17
  104. package/dist/packages/core/src/helpers/generateHTML.d.ts +0 -8
  105. package/dist/packages/core/src/helpers/generateJSON.d.ts +0 -8
  106. package/dist/packages/core/src/helpers/generateText.d.ts +0 -12
  107. package/dist/packages/core/src/helpers/getAttributes.d.ts +0 -9
  108. package/dist/packages/core/src/helpers/getAttributesFromExtensions.d.ts +0 -6
  109. package/dist/packages/core/src/helpers/getChangedRanges.d.ts +0 -11
  110. package/dist/packages/core/src/helpers/getDebugJSON.d.ts +0 -8
  111. package/dist/packages/core/src/helpers/getExtensionField.d.ts +0 -9
  112. package/dist/packages/core/src/helpers/getHTMLFromFragment.d.ts +0 -2
  113. package/dist/packages/core/src/helpers/getMarkAttributes.d.ts +0 -3
  114. package/dist/packages/core/src/helpers/getMarkRange.d.ts +0 -3
  115. package/dist/packages/core/src/helpers/getMarkType.d.ts +0 -2
  116. package/dist/packages/core/src/helpers/getMarksBetween.d.ts +0 -3
  117. package/dist/packages/core/src/helpers/getNodeAtPosition.d.ts +0 -11
  118. package/dist/packages/core/src/helpers/getNodeAttributes.d.ts +0 -3
  119. package/dist/packages/core/src/helpers/getNodeType.d.ts +0 -2
  120. package/dist/packages/core/src/helpers/getRenderedAttributes.d.ts +0 -3
  121. package/dist/packages/core/src/helpers/getSchema.d.ts +0 -4
  122. package/dist/packages/core/src/helpers/getSchemaByResolvedExtensions.d.ts +0 -10
  123. package/dist/packages/core/src/helpers/getSchemaTypeByName.d.ts +0 -8
  124. package/dist/packages/core/src/helpers/getSchemaTypeNameByName.d.ts +0 -8
  125. package/dist/packages/core/src/helpers/getSplittedAttributes.d.ts +0 -9
  126. package/dist/packages/core/src/helpers/getText.d.ts +0 -15
  127. package/dist/packages/core/src/helpers/getTextBetween.d.ts +0 -14
  128. package/dist/packages/core/src/helpers/getTextContentFromNodes.d.ts +0 -8
  129. package/dist/packages/core/src/helpers/getTextSerializersFromSchema.d.ts +0 -8
  130. package/dist/packages/core/src/helpers/index.d.ts +0 -50
  131. package/dist/packages/core/src/helpers/injectExtensionAttributesToParseRule.d.ts +0 -9
  132. package/dist/packages/core/src/helpers/isActive.d.ts +0 -2
  133. package/dist/packages/core/src/helpers/isAtEndOfNode.d.ts +0 -2
  134. package/dist/packages/core/src/helpers/isAtStartOfNode.d.ts +0 -2
  135. package/dist/packages/core/src/helpers/isExtensionRulesEnabled.d.ts +0 -2
  136. package/dist/packages/core/src/helpers/isList.d.ts +0 -2
  137. package/dist/packages/core/src/helpers/isMarkActive.d.ts +0 -3
  138. package/dist/packages/core/src/helpers/isNodeActive.d.ts +0 -3
  139. package/dist/packages/core/src/helpers/isNodeEmpty.d.ts +0 -8
  140. package/dist/packages/core/src/helpers/isNodeSelection.d.ts +0 -2
  141. package/dist/packages/core/src/helpers/isTextSelection.d.ts +0 -2
  142. package/dist/packages/core/src/helpers/posToDOMRect.d.ts +0 -2
  143. package/dist/packages/core/src/helpers/resolveFocusPosition.d.ts +0 -4
  144. package/dist/packages/core/src/helpers/selectionToInsertionEnd.d.ts +0 -2
  145. package/dist/packages/core/src/helpers/splitExtensions.d.ts +0 -9
  146. package/dist/packages/core/src/index.d.ts +0 -24
  147. package/dist/packages/core/src/inputRules/index.d.ts +0 -5
  148. package/dist/packages/core/src/inputRules/markInputRule.d.ts +0 -13
  149. package/dist/packages/core/src/inputRules/nodeInputRule.d.ts +0 -23
  150. package/dist/packages/core/src/inputRules/textInputRule.d.ts +0 -10
  151. package/dist/packages/core/src/inputRules/textblockTypeInputRule.d.ts +0 -15
  152. package/dist/packages/core/src/inputRules/wrappingInputRule.d.ts +0 -28
  153. package/dist/packages/core/src/pasteRules/index.d.ts +0 -3
  154. package/dist/packages/core/src/pasteRules/markPasteRule.d.ts +0 -13
  155. package/dist/packages/core/src/pasteRules/nodePasteRule.d.ts +0 -13
  156. package/dist/packages/core/src/pasteRules/textPasteRule.d.ts +0 -10
  157. package/dist/packages/core/src/style.d.ts +0 -1
  158. package/dist/packages/core/src/types.d.ts +0 -253
  159. package/dist/packages/core/src/utilities/callOrReturn.d.ts +0 -9
  160. package/dist/packages/core/src/utilities/createStyleTag.d.ts +0 -1
  161. package/dist/packages/core/src/utilities/deleteProps.d.ts +0 -6
  162. package/dist/packages/core/src/utilities/elementFromString.d.ts +0 -1
  163. package/dist/packages/core/src/utilities/escapeForRegEx.d.ts +0 -1
  164. package/dist/packages/core/src/utilities/findDuplicates.d.ts +0 -1
  165. package/dist/packages/core/src/utilities/fromString.d.ts +0 -1
  166. package/dist/packages/core/src/utilities/index.d.ts +0 -20
  167. package/dist/packages/core/src/utilities/isAndroid.d.ts +0 -1
  168. package/dist/packages/core/src/utilities/isEmptyObject.d.ts +0 -1
  169. package/dist/packages/core/src/utilities/isFunction.d.ts +0 -1
  170. package/dist/packages/core/src/utilities/isMacOS.d.ts +0 -1
  171. package/dist/packages/core/src/utilities/isNumber.d.ts +0 -1
  172. package/dist/packages/core/src/utilities/isPlainObject.d.ts +0 -1
  173. package/dist/packages/core/src/utilities/isRegExp.d.ts +0 -1
  174. package/dist/packages/core/src/utilities/isString.d.ts +0 -1
  175. package/dist/packages/core/src/utilities/isiOS.d.ts +0 -1
  176. package/dist/packages/core/src/utilities/mergeAttributes.d.ts +0 -1
  177. package/dist/packages/core/src/utilities/mergeDeep.d.ts +0 -1
  178. package/dist/packages/core/src/utilities/minMax.d.ts +0 -1
  179. package/dist/packages/core/src/utilities/objectIncludes.d.ts +0 -8
  180. package/dist/packages/core/src/utilities/removeDuplicates.d.ts +0 -8
  181. package/dist/packages/extension-bubble-menu/src/bubble-menu-plugin.d.ts +0 -99
  182. package/dist/packages/extension-bubble-menu/src/bubble-menu.d.ts +0 -15
  183. package/dist/packages/extension-bubble-menu/src/index.d.ts +0 -4
  184. package/dist/packages/extension-floating-menu/src/floating-menu-plugin.d.ts +0 -81
  185. package/dist/packages/extension-floating-menu/src/floating-menu.d.ts +0 -15
  186. package/dist/packages/extension-floating-menu/src/index.d.ts +0 -4
  187. package/dist/packages/react/src/BubbleMenu.d.ts +0 -13
  188. package/dist/packages/react/src/Context.d.ts +0 -23
  189. package/dist/packages/react/src/Editor.d.ts +0 -12
  190. package/dist/packages/react/src/EditorContent.d.ts +0 -24
  191. package/dist/packages/react/src/FloatingMenu.d.ts +0 -11
  192. package/dist/packages/react/src/NodeViewContent.d.ts +0 -6
  193. package/dist/packages/react/src/NodeViewWrapper.d.ts +0 -6
  194. package/dist/packages/react/src/ReactNodeViewRenderer.d.ts +0 -16
  195. package/dist/packages/react/src/ReactRenderer.d.ts +0 -62
  196. package/dist/packages/react/src/index.d.ts +0 -13
  197. package/dist/packages/react/src/useEditor.d.ts +0 -39
  198. package/dist/packages/react/src/useEditorState.d.ts +0 -22
  199. package/dist/packages/react/src/useReactNodeView.d.ts +0 -6
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,63 +35,76 @@ 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
- // TODO in the next major release, we should throw an error here
85
102
  if (isDev) {
86
103
  /**
87
104
  * Throw an error in development, to make sure the developer is aware that tiptap cannot be SSR'd
88
105
  * and that they need to set `immediatelyRender` to `false` to avoid hydration mismatches.
89
106
  */
90
- console.warn(
107
+ throw new Error(
91
108
  'Tiptap Error: SSR has been detected, please set `immediatelyRender` explicitly to `false` to avoid hydration mismatches.',
92
109
  )
93
110
  }
@@ -97,70 +114,206 @@ export function useEditor(
97
114
  }
98
115
 
99
116
  // Default to immediately rendering when client-side rendering
100
- return createEditor(mostRecentOptions)
117
+ return this.createEditor()
101
118
  }
102
119
 
103
- if (options.immediatelyRender && isSSR && isDev) {
120
+ if (this.options.current.immediatelyRender && isSSR && isDev) {
104
121
  // 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
122
  throw new Error(
106
123
  '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
124
  )
108
125
  }
109
126
 
110
- if (options.immediatelyRender) {
111
- return createEditor(mostRecentOptions)
127
+ if (this.options.current.immediatelyRender) {
128
+ return this.createEditor()
112
129
  }
113
130
 
114
131
  return null
115
- })
116
- const mostRecentEditor = useRef<Editor | null>(editor)
132
+ }
117
133
 
118
- mostRecentEditor.current = editor
134
+ /**
135
+ * Create a new editor instance. And attach event listeners.
136
+ */
137
+ private createEditor(): Editor {
138
+ const optionsToApply: Partial<EditorOptions> = {
139
+ ...this.options.current,
140
+ // Always call the most recent version of the callback function by default
141
+ onBeforeCreate: (...args) => this.options.current.onBeforeCreate?.(...args),
142
+ onBlur: (...args) => this.options.current.onBlur?.(...args),
143
+ onCreate: (...args) => this.options.current.onCreate?.(...args),
144
+ onDestroy: (...args) => this.options.current.onDestroy?.(...args),
145
+ onFocus: (...args) => this.options.current.onFocus?.(...args),
146
+ onSelectionUpdate: (...args) => this.options.current.onSelectionUpdate?.(...args),
147
+ onTransaction: (...args) => this.options.current.onTransaction?.(...args),
148
+ onUpdate: (...args) => this.options.current.onUpdate?.(...args),
149
+ onContentError: (...args) => this.options.current.onContentError?.(...args),
150
+ }
151
+ const editor = new Editor(optionsToApply)
119
152
 
120
- useDebugValue(editor)
153
+ // no need to keep track of the event listeners, they will be removed when the editor is destroyed
121
154
 
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
- }
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
+ if (this.editor && !this.editor.isDestroyed) {
220
+ // Editor instance already exists
221
+ if (this.previousDeps === null) {
222
+ // If lastDeps has not yet been initialized, reuse the current editor instance
223
+ this.previousDeps = deps
224
+ return
225
+ }
226
+ const depsAreEqual = this.previousDeps.length === deps.length
227
+ && this.previousDeps.every((dep, index) => dep === deps[index])
146
228
 
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)
229
+ if (depsAreEqual) {
230
+ // deps exist and are equal, no need to recreate
231
+ return
232
+ }
233
+ }
151
234
 
152
- return () => destroyUnusedEditor(editorInstance)
235
+ if (this.editor && !this.editor.isDestroyed) {
236
+ // Destroy the editor instance if it exists
237
+ this.editor.destroy()
153
238
  }
154
239
 
155
- // We need to destroy the editor instance and re-initialize it
156
- // when the deps array changes
157
- editorInstance.destroy()
240
+ this.setEditor(this.createEditor())
241
+
242
+ // Update the lastDeps to the current deps
243
+ this.previousDeps = deps
244
+ }
245
+
246
+ /**
247
+ * Schedule the destruction of the editor instance.
248
+ * This will only destroy the editor if it was not mounted on the next tick.
249
+ * This is to avoid destroying the editor instance when it's actually still mounted.
250
+ */
251
+ private scheduleDestroy() {
252
+ const currentInstanceId = this.instanceId
253
+ const currentEditor = this.editor
158
254
 
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)
255
+ // Wait a tick to see if the component is still mounted
256
+ this.scheduledDestructionTimeout = setTimeout(() => {
257
+ if (this.isComponentMounted && this.instanceId === currentInstanceId) {
258
+ // If still mounted on the next tick, with the same instanceId, do not destroy the editor
259
+ if (currentEditor) {
260
+ // just re-apply options as they might have changed
261
+ currentEditor.setOptions(this.options.current)
262
+ }
263
+ return
264
+ }
265
+ if (currentEditor && !currentEditor.isDestroyed) {
266
+ currentEditor.destroy()
267
+ if (this.instanceId === currentInstanceId) {
268
+ this.setEditor(null)
269
+ }
270
+ }
271
+ }, 0)
272
+ }
273
+ }
274
+
275
+ /**
276
+ * This hook allows you to create an editor instance.
277
+ * @param options The editor options
278
+ * @param deps The dependencies to watch for changes
279
+ * @returns The editor instance
280
+ * @example const editor = useEditor({ extensions: [...] })
281
+ */
282
+ export function useEditor(
283
+ options: UseEditorOptions & { immediatelyRender: true },
284
+ deps?: DependencyList
285
+ ): Editor;
286
+
287
+ /**
288
+ * This hook allows you to create an editor instance.
289
+ * @param options The editor options
290
+ * @param deps The dependencies to watch for changes
291
+ * @returns The editor instance
292
+ * @example const editor = useEditor({ extensions: [...] })
293
+ */
294
+ export function useEditor(options?: UseEditorOptions, deps?: DependencyList): Editor | null;
295
+
296
+ export function useEditor(
297
+ options: UseEditorOptions = {},
298
+ deps: DependencyList = [],
299
+ ): Editor | null {
300
+ const mostRecentOptions = useRef(options)
301
+
302
+ mostRecentOptions.current = options
303
+
304
+ const [instanceManager] = useState(() => new EditorInstanceManager(mostRecentOptions))
305
+
306
+ const editor = useSyncExternalStore(
307
+ instanceManager.subscribe,
308
+ instanceManager.getEditor,
309
+ instanceManager.getServerSnapshot,
310
+ )
311
+
312
+ useDebugValue(editor)
313
+
314
+ // This effect will handle creating/updating the editor instance
315
+ // eslint-disable-next-line react-hooks/exhaustive-deps
316
+ useEffect(instanceManager.onRender(deps))
164
317
 
165
318
  // The default behavior is to re-render on each transaction
166
319
  // 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