@tiptap/react 3.0.0 → 3.0.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 (215) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +5 -1
  3. package/dist/index.cjs +1030 -1163
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.cts +350 -0
  6. package/dist/index.d.ts +350 -0
  7. package/dist/index.js +970 -1138
  8. package/dist/index.js.map +1 -1
  9. package/dist/menus/index.cjs +142 -0
  10. package/dist/menus/index.cjs.map +1 -0
  11. package/dist/menus/index.d.cts +19 -0
  12. package/dist/menus/index.d.ts +19 -0
  13. package/dist/menus/index.js +104 -0
  14. package/dist/menus/index.js.map +1 -0
  15. package/package.json +34 -21
  16. package/src/Context.tsx +18 -12
  17. package/src/Editor.ts +10 -11
  18. package/src/EditorContent.tsx +104 -64
  19. package/src/NodeViewContent.tsx +13 -8
  20. package/src/NodeViewWrapper.tsx +3 -2
  21. package/src/ReactMarkViewRenderer.tsx +111 -0
  22. package/src/ReactNodeViewRenderer.tsx +184 -67
  23. package/src/ReactRenderer.tsx +152 -51
  24. package/src/index.ts +2 -3
  25. package/src/menus/BubbleMenu.tsx +68 -0
  26. package/src/menus/FloatingMenu.tsx +68 -0
  27. package/src/menus/index.ts +2 -0
  28. package/src/types.ts +6 -0
  29. package/src/useEditor.ts +286 -166
  30. package/src/useEditorState.ts +133 -85
  31. package/src/useReactNodeView.ts +21 -5
  32. package/dist/index.umd.js +0 -1219
  33. package/dist/index.umd.js.map +0 -1
  34. package/dist/packages/core/src/CommandManager.d.ts +0 -20
  35. package/dist/packages/core/src/Editor.d.ts +0 -161
  36. package/dist/packages/core/src/EventEmitter.d.ts +0 -11
  37. package/dist/packages/core/src/Extension.d.ts +0 -343
  38. package/dist/packages/core/src/ExtensionManager.d.ts +0 -55
  39. package/dist/packages/core/src/InputRule.d.ts +0 -42
  40. package/dist/packages/core/src/Mark.d.ts +0 -451
  41. package/dist/packages/core/src/Node.d.ts +0 -611
  42. package/dist/packages/core/src/NodePos.d.ts +0 -44
  43. package/dist/packages/core/src/NodeView.d.ts +0 -31
  44. package/dist/packages/core/src/PasteRule.d.ts +0 -50
  45. package/dist/packages/core/src/Tracker.d.ts +0 -11
  46. package/dist/packages/core/src/commands/blur.d.ts +0 -13
  47. package/dist/packages/core/src/commands/clearContent.d.ts +0 -14
  48. package/dist/packages/core/src/commands/clearNodes.d.ts +0 -13
  49. package/dist/packages/core/src/commands/command.d.ts +0 -18
  50. package/dist/packages/core/src/commands/createParagraphNear.d.ts +0 -13
  51. package/dist/packages/core/src/commands/cut.d.ts +0 -20
  52. package/dist/packages/core/src/commands/deleteCurrentNode.d.ts +0 -13
  53. package/dist/packages/core/src/commands/deleteNode.d.ts +0 -15
  54. package/dist/packages/core/src/commands/deleteRange.d.ts +0 -14
  55. package/dist/packages/core/src/commands/deleteSelection.d.ts +0 -13
  56. package/dist/packages/core/src/commands/enter.d.ts +0 -13
  57. package/dist/packages/core/src/commands/exitCode.d.ts +0 -13
  58. package/dist/packages/core/src/commands/extendMarkRange.d.ts +0 -25
  59. package/dist/packages/core/src/commands/first.d.ts +0 -14
  60. package/dist/packages/core/src/commands/focus.d.ts +0 -27
  61. package/dist/packages/core/src/commands/forEach.d.ts +0 -14
  62. package/dist/packages/core/src/commands/index.d.ts +0 -55
  63. package/dist/packages/core/src/commands/insertContent.d.ts +0 -34
  64. package/dist/packages/core/src/commands/insertContentAt.d.ts +0 -47
  65. package/dist/packages/core/src/commands/join.d.ts +0 -41
  66. package/dist/packages/core/src/commands/joinItemBackward.d.ts +0 -13
  67. package/dist/packages/core/src/commands/joinItemForward.d.ts +0 -13
  68. package/dist/packages/core/src/commands/joinTextblockBackward.d.ts +0 -12
  69. package/dist/packages/core/src/commands/joinTextblockForward.d.ts +0 -12
  70. package/dist/packages/core/src/commands/keyboardShortcut.d.ts +0 -14
  71. package/dist/packages/core/src/commands/lift.d.ts +0 -17
  72. package/dist/packages/core/src/commands/liftEmptyBlock.d.ts +0 -13
  73. package/dist/packages/core/src/commands/liftListItem.d.ts +0 -15
  74. package/dist/packages/core/src/commands/newlineInCode.d.ts +0 -13
  75. package/dist/packages/core/src/commands/resetAttributes.d.ts +0 -16
  76. package/dist/packages/core/src/commands/scrollIntoView.d.ts +0 -13
  77. package/dist/packages/core/src/commands/selectAll.d.ts +0 -13
  78. package/dist/packages/core/src/commands/selectNodeBackward.d.ts +0 -13
  79. package/dist/packages/core/src/commands/selectNodeForward.d.ts +0 -13
  80. package/dist/packages/core/src/commands/selectParentNode.d.ts +0 -13
  81. package/dist/packages/core/src/commands/selectTextblockEnd.d.ts +0 -13
  82. package/dist/packages/core/src/commands/selectTextblockStart.d.ts +0 -13
  83. package/dist/packages/core/src/commands/setContent.d.ts +0 -40
  84. package/dist/packages/core/src/commands/setMark.d.ts +0 -15
  85. package/dist/packages/core/src/commands/setMeta.d.ts +0 -15
  86. package/dist/packages/core/src/commands/setNode.d.ts +0 -16
  87. package/dist/packages/core/src/commands/setNodeSelection.d.ts +0 -14
  88. package/dist/packages/core/src/commands/setTextSelection.d.ts +0 -14
  89. package/dist/packages/core/src/commands/sinkListItem.d.ts +0 -15
  90. package/dist/packages/core/src/commands/splitBlock.d.ts +0 -17
  91. package/dist/packages/core/src/commands/splitListItem.d.ts +0 -15
  92. package/dist/packages/core/src/commands/toggleList.d.ts +0 -18
  93. package/dist/packages/core/src/commands/toggleMark.d.ts +0 -30
  94. package/dist/packages/core/src/commands/toggleNode.d.ts +0 -17
  95. package/dist/packages/core/src/commands/toggleWrap.d.ts +0 -16
  96. package/dist/packages/core/src/commands/undoInputRule.d.ts +0 -13
  97. package/dist/packages/core/src/commands/unsetAllMarks.d.ts +0 -13
  98. package/dist/packages/core/src/commands/unsetMark.d.ts +0 -25
  99. package/dist/packages/core/src/commands/updateAttributes.d.ts +0 -24
  100. package/dist/packages/core/src/commands/wrapIn.d.ts +0 -16
  101. package/dist/packages/core/src/commands/wrapInList.d.ts +0 -16
  102. package/dist/packages/core/src/extensions/clipboardTextSerializer.d.ts +0 -5
  103. package/dist/packages/core/src/extensions/commands.d.ts +0 -3
  104. package/dist/packages/core/src/extensions/editable.d.ts +0 -2
  105. package/dist/packages/core/src/extensions/focusEvents.d.ts +0 -2
  106. package/dist/packages/core/src/extensions/index.d.ts +0 -6
  107. package/dist/packages/core/src/extensions/keymap.d.ts +0 -2
  108. package/dist/packages/core/src/extensions/tabindex.d.ts +0 -2
  109. package/dist/packages/core/src/helpers/combineTransactionSteps.d.ts +0 -10
  110. package/dist/packages/core/src/helpers/createChainableState.d.ts +0 -10
  111. package/dist/packages/core/src/helpers/createDocument.d.ts +0 -12
  112. package/dist/packages/core/src/helpers/createNodeFromContent.d.ts +0 -15
  113. package/dist/packages/core/src/helpers/defaultBlockAt.d.ts +0 -7
  114. package/dist/packages/core/src/helpers/findChildren.d.ts +0 -9
  115. package/dist/packages/core/src/helpers/findChildrenInRange.d.ts +0 -10
  116. package/dist/packages/core/src/helpers/findParentNode.d.ts +0 -16
  117. package/dist/packages/core/src/helpers/findParentNodeClosestToPos.d.ts +0 -17
  118. package/dist/packages/core/src/helpers/generateHTML.d.ts +0 -8
  119. package/dist/packages/core/src/helpers/generateJSON.d.ts +0 -8
  120. package/dist/packages/core/src/helpers/generateText.d.ts +0 -12
  121. package/dist/packages/core/src/helpers/getAttributes.d.ts +0 -9
  122. package/dist/packages/core/src/helpers/getAttributesFromExtensions.d.ts +0 -6
  123. package/dist/packages/core/src/helpers/getChangedRanges.d.ts +0 -11
  124. package/dist/packages/core/src/helpers/getDebugJSON.d.ts +0 -8
  125. package/dist/packages/core/src/helpers/getExtensionField.d.ts +0 -9
  126. package/dist/packages/core/src/helpers/getHTMLFromFragment.d.ts +0 -2
  127. package/dist/packages/core/src/helpers/getMarkAttributes.d.ts +0 -3
  128. package/dist/packages/core/src/helpers/getMarkRange.d.ts +0 -3
  129. package/dist/packages/core/src/helpers/getMarkType.d.ts +0 -2
  130. package/dist/packages/core/src/helpers/getMarksBetween.d.ts +0 -3
  131. package/dist/packages/core/src/helpers/getNodeAtPosition.d.ts +0 -11
  132. package/dist/packages/core/src/helpers/getNodeAttributes.d.ts +0 -3
  133. package/dist/packages/core/src/helpers/getNodeType.d.ts +0 -2
  134. package/dist/packages/core/src/helpers/getRenderedAttributes.d.ts +0 -3
  135. package/dist/packages/core/src/helpers/getSchema.d.ts +0 -4
  136. package/dist/packages/core/src/helpers/getSchemaByResolvedExtensions.d.ts +0 -10
  137. package/dist/packages/core/src/helpers/getSchemaTypeByName.d.ts +0 -8
  138. package/dist/packages/core/src/helpers/getSchemaTypeNameByName.d.ts +0 -8
  139. package/dist/packages/core/src/helpers/getSplittedAttributes.d.ts +0 -9
  140. package/dist/packages/core/src/helpers/getText.d.ts +0 -15
  141. package/dist/packages/core/src/helpers/getTextBetween.d.ts +0 -14
  142. package/dist/packages/core/src/helpers/getTextContentFromNodes.d.ts +0 -8
  143. package/dist/packages/core/src/helpers/getTextSerializersFromSchema.d.ts +0 -8
  144. package/dist/packages/core/src/helpers/index.d.ts +0 -50
  145. package/dist/packages/core/src/helpers/injectExtensionAttributesToParseRule.d.ts +0 -9
  146. package/dist/packages/core/src/helpers/isActive.d.ts +0 -2
  147. package/dist/packages/core/src/helpers/isAtEndOfNode.d.ts +0 -2
  148. package/dist/packages/core/src/helpers/isAtStartOfNode.d.ts +0 -2
  149. package/dist/packages/core/src/helpers/isExtensionRulesEnabled.d.ts +0 -2
  150. package/dist/packages/core/src/helpers/isList.d.ts +0 -2
  151. package/dist/packages/core/src/helpers/isMarkActive.d.ts +0 -3
  152. package/dist/packages/core/src/helpers/isNodeActive.d.ts +0 -3
  153. package/dist/packages/core/src/helpers/isNodeEmpty.d.ts +0 -2
  154. package/dist/packages/core/src/helpers/isNodeSelection.d.ts +0 -2
  155. package/dist/packages/core/src/helpers/isTextSelection.d.ts +0 -2
  156. package/dist/packages/core/src/helpers/posToDOMRect.d.ts +0 -2
  157. package/dist/packages/core/src/helpers/resolveFocusPosition.d.ts +0 -4
  158. package/dist/packages/core/src/helpers/selectionToInsertionEnd.d.ts +0 -2
  159. package/dist/packages/core/src/helpers/splitExtensions.d.ts +0 -9
  160. package/dist/packages/core/src/index.d.ts +0 -24
  161. package/dist/packages/core/src/inputRules/index.d.ts +0 -5
  162. package/dist/packages/core/src/inputRules/markInputRule.d.ts +0 -13
  163. package/dist/packages/core/src/inputRules/nodeInputRule.d.ts +0 -23
  164. package/dist/packages/core/src/inputRules/textInputRule.d.ts +0 -10
  165. package/dist/packages/core/src/inputRules/textblockTypeInputRule.d.ts +0 -15
  166. package/dist/packages/core/src/inputRules/wrappingInputRule.d.ts +0 -28
  167. package/dist/packages/core/src/pasteRules/index.d.ts +0 -3
  168. package/dist/packages/core/src/pasteRules/markPasteRule.d.ts +0 -13
  169. package/dist/packages/core/src/pasteRules/nodePasteRule.d.ts +0 -13
  170. package/dist/packages/core/src/pasteRules/textPasteRule.d.ts +0 -10
  171. package/dist/packages/core/src/style.d.ts +0 -1
  172. package/dist/packages/core/src/types.d.ts +0 -255
  173. package/dist/packages/core/src/utilities/callOrReturn.d.ts +0 -9
  174. package/dist/packages/core/src/utilities/createStyleTag.d.ts +0 -1
  175. package/dist/packages/core/src/utilities/deleteProps.d.ts +0 -6
  176. package/dist/packages/core/src/utilities/elementFromString.d.ts +0 -1
  177. package/dist/packages/core/src/utilities/escapeForRegEx.d.ts +0 -1
  178. package/dist/packages/core/src/utilities/findDuplicates.d.ts +0 -1
  179. package/dist/packages/core/src/utilities/fromString.d.ts +0 -1
  180. package/dist/packages/core/src/utilities/index.d.ts +0 -20
  181. package/dist/packages/core/src/utilities/isAndroid.d.ts +0 -1
  182. package/dist/packages/core/src/utilities/isEmptyObject.d.ts +0 -1
  183. package/dist/packages/core/src/utilities/isFunction.d.ts +0 -1
  184. package/dist/packages/core/src/utilities/isMacOS.d.ts +0 -1
  185. package/dist/packages/core/src/utilities/isNumber.d.ts +0 -1
  186. package/dist/packages/core/src/utilities/isPlainObject.d.ts +0 -1
  187. package/dist/packages/core/src/utilities/isRegExp.d.ts +0 -1
  188. package/dist/packages/core/src/utilities/isString.d.ts +0 -1
  189. package/dist/packages/core/src/utilities/isiOS.d.ts +0 -1
  190. package/dist/packages/core/src/utilities/mergeAttributes.d.ts +0 -1
  191. package/dist/packages/core/src/utilities/mergeDeep.d.ts +0 -1
  192. package/dist/packages/core/src/utilities/minMax.d.ts +0 -1
  193. package/dist/packages/core/src/utilities/objectIncludes.d.ts +0 -8
  194. package/dist/packages/core/src/utilities/removeDuplicates.d.ts +0 -8
  195. package/dist/packages/extension-bubble-menu/src/bubble-menu-plugin.d.ts +0 -76
  196. package/dist/packages/extension-bubble-menu/src/bubble-menu.d.ts +0 -15
  197. package/dist/packages/extension-bubble-menu/src/index.d.ts +0 -4
  198. package/dist/packages/extension-floating-menu/src/floating-menu-plugin.d.ts +0 -66
  199. package/dist/packages/extension-floating-menu/src/floating-menu.d.ts +0 -15
  200. package/dist/packages/extension-floating-menu/src/index.d.ts +0 -4
  201. package/dist/packages/react/src/BubbleMenu.d.ts +0 -11
  202. package/dist/packages/react/src/Context.d.ts +0 -23
  203. package/dist/packages/react/src/Editor.d.ts +0 -12
  204. package/dist/packages/react/src/EditorContent.d.ts +0 -24
  205. package/dist/packages/react/src/FloatingMenu.d.ts +0 -10
  206. package/dist/packages/react/src/NodeViewContent.d.ts +0 -6
  207. package/dist/packages/react/src/NodeViewWrapper.d.ts +0 -6
  208. package/dist/packages/react/src/ReactNodeViewRenderer.d.ts +0 -16
  209. package/dist/packages/react/src/ReactRenderer.d.ts +0 -62
  210. package/dist/packages/react/src/index.d.ts +0 -13
  211. package/dist/packages/react/src/useEditor.d.ts +0 -39
  212. package/dist/packages/react/src/useEditorState.d.ts +0 -22
  213. package/dist/packages/react/src/useReactNodeView.d.ts +0 -6
  214. package/src/BubbleMenu.tsx +0 -57
  215. package/src/FloatingMenu.tsx +0 -64
package/dist/index.cjs CHANGED
@@ -1,1219 +1,1086 @@
1
- 'use strict';
2
-
3
- var extensionBubbleMenu = require('@tiptap/extension-bubble-menu');
4
- var React = require('react');
5
- var ReactDOM = require('react-dom');
6
- var core = require('@tiptap/core');
7
- var extensionFloatingMenu = require('@tiptap/extension-floating-menu');
8
-
9
- const mergeRefs = (...refs) => {
10
- return (node) => {
11
- refs.forEach(ref => {
12
- if (typeof ref === 'function') {
13
- ref(node);
14
- }
15
- else if (ref) {
16
- ref.current = node;
17
- }
18
- });
19
- };
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
20
11
  };
21
- const Portals = ({ renderers }) => {
22
- return (React.createElement(React.Fragment, null, Object.entries(renderers).map(([key, renderer]) => {
23
- return ReactDOM.createPortal(renderer.reactElement, renderer.element, key);
24
- })));
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
25
19
  };
26
- class PureEditorContent extends React.Component {
27
- constructor(props) {
28
- super(props);
29
- this.editorContentRef = React.createRef();
30
- this.initialized = false;
31
- this.state = {
32
- renderers: {},
33
- };
34
- }
35
- componentDidMount() {
36
- this.init();
37
- }
38
- componentDidUpdate() {
39
- this.init();
20
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/index.ts
32
+ var index_exports = {};
33
+ __export(index_exports, {
34
+ EditorConsumer: () => EditorConsumer,
35
+ EditorContent: () => EditorContent,
36
+ EditorContext: () => EditorContext,
37
+ EditorProvider: () => EditorProvider,
38
+ MarkViewContent: () => MarkViewContent,
39
+ NodeViewContent: () => NodeViewContent,
40
+ NodeViewWrapper: () => NodeViewWrapper,
41
+ PureEditorContent: () => PureEditorContent,
42
+ ReactMarkView: () => ReactMarkView,
43
+ ReactMarkViewContext: () => ReactMarkViewContext,
44
+ ReactMarkViewRenderer: () => ReactMarkViewRenderer,
45
+ ReactNodeView: () => ReactNodeView,
46
+ ReactNodeViewContentProvider: () => ReactNodeViewContentProvider,
47
+ ReactNodeViewContext: () => ReactNodeViewContext,
48
+ ReactNodeViewRenderer: () => ReactNodeViewRenderer,
49
+ ReactRenderer: () => ReactRenderer,
50
+ useCurrentEditor: () => useCurrentEditor,
51
+ useEditor: () => useEditor,
52
+ useEditorState: () => useEditorState,
53
+ useReactNodeView: () => useReactNodeView
54
+ });
55
+ module.exports = __toCommonJS(index_exports);
56
+
57
+ // src/Context.tsx
58
+ var import_react5 = require("react");
59
+
60
+ // src/EditorContent.tsx
61
+ var import_react = __toESM(require("react"), 1);
62
+ var import_react_dom = __toESM(require("react-dom"), 1);
63
+ var import_shim = require("use-sync-external-store/shim/index.js");
64
+ var import_jsx_runtime = require("react/jsx-runtime");
65
+ var mergeRefs = (...refs) => {
66
+ return (node) => {
67
+ refs.forEach((ref) => {
68
+ if (typeof ref === "function") {
69
+ ref(node);
70
+ } else if (ref) {
71
+ ;
72
+ ref.current = node;
73
+ }
74
+ });
75
+ };
76
+ };
77
+ var Portals = ({ contentComponent }) => {
78
+ const renderers = (0, import_shim.useSyncExternalStore)(
79
+ contentComponent.subscribe,
80
+ contentComponent.getSnapshot,
81
+ contentComponent.getServerSnapshot
82
+ );
83
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: Object.values(renderers) });
84
+ };
85
+ function getInstance() {
86
+ const subscribers = /* @__PURE__ */ new Set();
87
+ let renderers = {};
88
+ return {
89
+ /**
90
+ * Subscribe to the editor instance's changes.
91
+ */
92
+ subscribe(callback) {
93
+ subscribers.add(callback);
94
+ return () => {
95
+ subscribers.delete(callback);
96
+ };
97
+ },
98
+ getSnapshot() {
99
+ return renderers;
100
+ },
101
+ getServerSnapshot() {
102
+ return renderers;
103
+ },
104
+ /**
105
+ * Adds a new NodeView Renderer to the editor.
106
+ */
107
+ setRenderer(id, renderer) {
108
+ renderers = {
109
+ ...renderers,
110
+ [id]: import_react_dom.default.createPortal(renderer.reactElement, renderer.element, id)
111
+ };
112
+ subscribers.forEach((subscriber) => subscriber());
113
+ },
114
+ /**
115
+ * Removes a NodeView Renderer from the editor.
116
+ */
117
+ removeRenderer(id) {
118
+ const nextRenderers = { ...renderers };
119
+ delete nextRenderers[id];
120
+ renderers = nextRenderers;
121
+ subscribers.forEach((subscriber) => subscriber());
40
122
  }
41
- init() {
42
- const { editor } = this.props;
43
- if (editor && !editor.isDestroyed && editor.options.element) {
44
- if (editor.contentComponent) {
45
- return;
123
+ };
124
+ }
125
+ var PureEditorContent = class extends import_react.default.Component {
126
+ constructor(props) {
127
+ var _a;
128
+ super(props);
129
+ this.editorContentRef = import_react.default.createRef();
130
+ this.initialized = false;
131
+ this.state = {
132
+ hasContentComponentInitialized: Boolean((_a = props.editor) == null ? void 0 : _a.contentComponent)
133
+ };
134
+ }
135
+ componentDidMount() {
136
+ this.init();
137
+ }
138
+ componentDidUpdate() {
139
+ this.init();
140
+ }
141
+ init() {
142
+ const editor = this.props.editor;
143
+ if (editor && !editor.isDestroyed && editor.options.element) {
144
+ if (editor.contentComponent) {
145
+ return;
146
+ }
147
+ const element = this.editorContentRef.current;
148
+ element.append(...editor.options.element.childNodes);
149
+ editor.setOptions({
150
+ element
151
+ });
152
+ editor.contentComponent = getInstance();
153
+ if (!this.state.hasContentComponentInitialized) {
154
+ this.unsubscribeToContentComponent = editor.contentComponent.subscribe(() => {
155
+ this.setState((prevState) => {
156
+ if (!prevState.hasContentComponentInitialized) {
157
+ return {
158
+ hasContentComponentInitialized: true
159
+ };
46
160
  }
47
- const element = this.editorContentRef.current;
48
- element.append(...editor.options.element.childNodes);
49
- editor.setOptions({
50
- element,
51
- });
52
- editor.contentComponent = this;
53
- editor.createNodeViews();
54
- this.initialized = true;
55
- }
56
- }
57
- maybeFlushSync(fn) {
58
- // Avoid calling flushSync until the editor is initialized.
59
- // Initialization happens during the componentDidMount or componentDidUpdate
60
- // lifecycle methods, and React doesn't allow calling flushSync from inside
61
- // a lifecycle method.
62
- if (this.initialized) {
63
- ReactDOM.flushSync(fn);
64
- }
65
- else {
66
- fn();
67
- }
68
- }
69
- setRenderer(id, renderer) {
70
- this.maybeFlushSync(() => {
71
- this.setState(({ renderers }) => ({
72
- renderers: {
73
- ...renderers,
74
- [id]: renderer,
75
- },
76
- }));
161
+ return prevState;
162
+ });
163
+ if (this.unsubscribeToContentComponent) {
164
+ this.unsubscribeToContentComponent();
165
+ }
77
166
  });
167
+ }
168
+ editor.createNodeViews();
169
+ this.initialized = true;
78
170
  }
79
- removeRenderer(id) {
80
- this.maybeFlushSync(() => {
81
- this.setState(({ renderers }) => {
82
- const nextRenderers = { ...renderers };
83
- delete nextRenderers[id];
84
- return { renderers: nextRenderers };
85
- });
86
- });
171
+ }
172
+ componentWillUnmount() {
173
+ var _a;
174
+ const editor = this.props.editor;
175
+ if (!editor) {
176
+ return;
87
177
  }
88
- componentWillUnmount() {
89
- const { editor } = this.props;
90
- if (!editor) {
91
- return;
92
- }
93
- this.initialized = false;
94
- if (!editor.isDestroyed) {
95
- editor.view.setProps({
96
- nodeViews: {},
97
- });
98
- }
99
- editor.contentComponent = null;
100
- if (!editor.options.element.firstChild) {
101
- return;
102
- }
103
- const newElement = document.createElement('div');
104
- newElement.append(...editor.options.element.childNodes);
105
- editor.setOptions({
106
- element: newElement,
107
- });
178
+ this.initialized = false;
179
+ if (!editor.isDestroyed) {
180
+ editor.view.setProps({
181
+ nodeViews: {}
182
+ });
108
183
  }
109
- render() {
110
- const { editor, innerRef, ...rest } = this.props;
111
- return (React.createElement(React.Fragment, null,
112
- React.createElement("div", { ref: mergeRefs(innerRef, this.editorContentRef), ...rest }),
113
- React.createElement(Portals, { renderers: this.state.renderers })));
184
+ if (this.unsubscribeToContentComponent) {
185
+ this.unsubscribeToContentComponent();
114
186
  }
115
- }
116
- // EditorContent should be re-created whenever the Editor instance changes
117
- const EditorContentWithKey = React.forwardRef((props, ref) => {
118
- const key = React.useMemo(() => {
119
- return Math.floor(Math.random() * 0xFFFFFFFF).toString();
187
+ editor.contentComponent = null;
188
+ if (!((_a = editor.options.element) == null ? void 0 : _a.firstChild)) {
189
+ return;
190
+ }
191
+ const newElement = document.createElement("div");
192
+ newElement.append(...editor.options.element.childNodes);
193
+ editor.setOptions({
194
+ element: newElement
195
+ });
196
+ }
197
+ render() {
198
+ const { editor, innerRef, ...rest } = this.props;
199
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
200
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { ref: mergeRefs(innerRef, this.editorContentRef), ...rest }),
201
+ (editor == null ? void 0 : editor.contentComponent) && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Portals, { contentComponent: editor.contentComponent })
202
+ ] });
203
+ }
204
+ };
205
+ var EditorContentWithKey = (0, import_react.forwardRef)(
206
+ (props, ref) => {
207
+ const key = import_react.default.useMemo(() => {
208
+ return Math.floor(Math.random() * 4294967295).toString();
120
209
  }, [props.editor]);
121
- // Can't use JSX here because it conflicts with the type definition of Vue's JSX, so use createElement
122
- return React.createElement(PureEditorContent, {
123
- key,
124
- innerRef: ref,
125
- ...props,
210
+ return import_react.default.createElement(PureEditorContent, {
211
+ key,
212
+ innerRef: ref,
213
+ ...props
126
214
  });
127
- });
128
- const EditorContent = React.memo(EditorContentWithKey);
129
-
130
- class Editor extends core.Editor {
131
- constructor() {
132
- super(...arguments);
133
- this.contentComponent = null;
215
+ }
216
+ );
217
+ var EditorContent = import_react.default.memo(EditorContentWithKey);
218
+
219
+ // src/useEditor.ts
220
+ var import_core = require("@tiptap/core");
221
+ var import_react4 = require("react");
222
+ var import_shim2 = require("use-sync-external-store/shim/index.js");
223
+
224
+ // src/useEditorState.ts
225
+ var import_react2 = __toESM(require("fast-deep-equal/es6/react.js"), 1);
226
+ var import_react3 = require("react");
227
+ var import_with_selector = require("use-sync-external-store/shim/with-selector.js");
228
+ var useIsomorphicLayoutEffect = typeof window !== "undefined" ? import_react3.useLayoutEffect : import_react3.useEffect;
229
+ var EditorStateManager = class {
230
+ constructor(initialEditor) {
231
+ this.transactionNumber = 0;
232
+ this.lastTransactionNumber = 0;
233
+ this.subscribers = /* @__PURE__ */ new Set();
234
+ this.editor = initialEditor;
235
+ this.lastSnapshot = { editor: initialEditor, transactionNumber: 0 };
236
+ this.getSnapshot = this.getSnapshot.bind(this);
237
+ this.getServerSnapshot = this.getServerSnapshot.bind(this);
238
+ this.watch = this.watch.bind(this);
239
+ this.subscribe = this.subscribe.bind(this);
240
+ }
241
+ /**
242
+ * Get the current editor instance.
243
+ */
244
+ getSnapshot() {
245
+ if (this.transactionNumber === this.lastTransactionNumber) {
246
+ return this.lastSnapshot;
134
247
  }
135
- }
136
-
137
- var withSelector = {exports: {}};
138
-
139
- var withSelector_production_min = {};
140
-
141
- var shim = {exports: {}};
142
-
143
- var useSyncExternalStoreShim_production_min = {};
144
-
145
- /**
146
- * @license React
147
- * use-sync-external-store-shim.production.min.js
148
- *
149
- * Copyright (c) Facebook, Inc. and its affiliates.
150
- *
151
- * This source code is licensed under the MIT license found in the
152
- * LICENSE file in the root directory of this source tree.
153
- */
154
-
155
- var hasRequiredUseSyncExternalStoreShim_production_min;
156
-
157
- function requireUseSyncExternalStoreShim_production_min () {
158
- if (hasRequiredUseSyncExternalStoreShim_production_min) return useSyncExternalStoreShim_production_min;
159
- hasRequiredUseSyncExternalStoreShim_production_min = 1;
160
- var e=React;function h(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var k="function"===typeof Object.is?Object.is:h,l=e.useState,m=e.useEffect,n=e.useLayoutEffect,p=e.useDebugValue;function q(a,b){var d=b(),f=l({inst:{value:d,getSnapshot:b}}),c=f[0].inst,g=f[1];n(function(){c.value=d;c.getSnapshot=b;r(c)&&g({inst:c});},[a,d,b]);m(function(){r(c)&&g({inst:c});return a(function(){r(c)&&g({inst:c});})},[a]);p(d);return d}
161
- function r(a){var b=a.getSnapshot;a=a.value;try{var d=b();return !k(a,d)}catch(f){return !0}}function t(a,b){return b()}var u="undefined"===typeof window||"undefined"===typeof window.document||"undefined"===typeof window.document.createElement?t:q;useSyncExternalStoreShim_production_min.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:u;
162
- return useSyncExternalStoreShim_production_min;
163
- }
164
-
165
- var useSyncExternalStoreShim_development = {};
166
-
167
- /**
168
- * @license React
169
- * use-sync-external-store-shim.development.js
170
- *
171
- * Copyright (c) Facebook, Inc. and its affiliates.
172
- *
173
- * This source code is licensed under the MIT license found in the
174
- * LICENSE file in the root directory of this source tree.
175
- */
176
-
177
- var hasRequiredUseSyncExternalStoreShim_development;
178
-
179
- function requireUseSyncExternalStoreShim_development () {
180
- if (hasRequiredUseSyncExternalStoreShim_development) return useSyncExternalStoreShim_development;
181
- hasRequiredUseSyncExternalStoreShim_development = 1;
182
-
183
- if (process.env.NODE_ENV !== "production") {
184
- (function() {
185
-
186
- /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
187
- if (
188
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
189
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===
190
- 'function'
191
- ) {
192
- __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
193
- }
194
- var React$1 = React;
195
-
196
- var ReactSharedInternals = React$1.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
197
-
198
- function error(format) {
199
- {
200
- {
201
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
202
- args[_key2 - 1] = arguments[_key2];
203
- }
204
-
205
- printWarning('error', format, args);
206
- }
207
- }
208
- }
209
-
210
- function printWarning(level, format, args) {
211
- // When changing this logic, you might want to also
212
- // update consoleWithStackDev.www.js as well.
213
- {
214
- var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
215
- var stack = ReactDebugCurrentFrame.getStackAddendum();
216
-
217
- if (stack !== '') {
218
- format += '%s';
219
- args = args.concat([stack]);
220
- } // eslint-disable-next-line react-internal/safe-string-coercion
221
-
222
-
223
- var argsWithFormat = args.map(function (item) {
224
- return String(item);
225
- }); // Careful: RN currently depends on this prefix
226
-
227
- argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
228
- // breaks IE9: https://github.com/facebook/react/issues/13610
229
- // eslint-disable-next-line react-internal/no-production-logging
230
-
231
- Function.prototype.apply.call(console[level], console, argsWithFormat);
232
- }
233
- }
234
-
235
- /**
236
- * inlined Object.is polyfill to avoid requiring consumers ship their own
237
- * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
238
- */
239
- function is(x, y) {
240
- return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
241
- ;
242
- }
243
-
244
- var objectIs = typeof Object.is === 'function' ? Object.is : is;
245
-
246
- // dispatch for CommonJS interop named imports.
247
-
248
- var useState = React$1.useState,
249
- useEffect = React$1.useEffect,
250
- useLayoutEffect = React$1.useLayoutEffect,
251
- useDebugValue = React$1.useDebugValue;
252
- var didWarnOld18Alpha = false;
253
- var didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works
254
- // because of a very particular set of implementation details and assumptions
255
- // -- change any one of them and it will break. The most important assumption
256
- // is that updates are always synchronous, because concurrent rendering is
257
- // only available in versions of React that also have a built-in
258
- // useSyncExternalStore API. And we only use this shim when the built-in API
259
- // does not exist.
260
- //
261
- // Do not assume that the clever hacks used by this hook also work in general.
262
- // The point of this shim is to replace the need for hacks by other libraries.
263
-
264
- function useSyncExternalStore(subscribe, getSnapshot, // Note: The shim does not use getServerSnapshot, because pre-18 versions of
265
- // React do not expose a way to check if we're hydrating. So users of the shim
266
- // will need to track that themselves and return the correct value
267
- // from `getSnapshot`.
268
- getServerSnapshot) {
269
- {
270
- if (!didWarnOld18Alpha) {
271
- if (React$1.startTransition !== undefined) {
272
- didWarnOld18Alpha = true;
273
-
274
- error('You are using an outdated, pre-release alpha of React 18 that ' + 'does not support useSyncExternalStore. The ' + 'use-sync-external-store shim will not work correctly. Upgrade ' + 'to a newer pre-release.');
275
- }
276
- }
277
- } // Read the current snapshot from the store on every render. Again, this
278
- // breaks the rules of React, and only works here because of specific
279
- // implementation details, most importantly that updates are
280
- // always synchronous.
281
-
282
-
283
- var value = getSnapshot();
284
-
285
- {
286
- if (!didWarnUncachedGetSnapshot) {
287
- var cachedValue = getSnapshot();
288
-
289
- if (!objectIs(value, cachedValue)) {
290
- error('The result of getSnapshot should be cached to avoid an infinite loop');
291
-
292
- didWarnUncachedGetSnapshot = true;
293
- }
294
- }
295
- } // Because updates are synchronous, we don't queue them. Instead we force a
296
- // re-render whenever the subscribed state changes by updating an some
297
- // arbitrary useState hook. Then, during render, we call getSnapshot to read
298
- // the current value.
299
- //
300
- // Because we don't actually use the state returned by the useState hook, we
301
- // can save a bit of memory by storing other stuff in that slot.
302
- //
303
- // To implement the early bailout, we need to track some things on a mutable
304
- // object. Usually, we would put that in a useRef hook, but we can stash it in
305
- // our useState hook instead.
306
- //
307
- // To force a re-render, we call forceUpdate({inst}). That works because the
308
- // new object always fails an equality check.
309
-
310
-
311
- var _useState = useState({
312
- inst: {
313
- value: value,
314
- getSnapshot: getSnapshot
315
- }
316
- }),
317
- inst = _useState[0].inst,
318
- forceUpdate = _useState[1]; // Track the latest getSnapshot function with a ref. This needs to be updated
319
- // in the layout phase so we can access it during the tearing check that
320
- // happens on subscribe.
321
-
322
-
323
- useLayoutEffect(function () {
324
- inst.value = value;
325
- inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the
326
- // commit phase if there was an interleaved mutation. In concurrent mode
327
- // this can happen all the time, but even in synchronous mode, an earlier
328
- // effect may have mutated the store.
329
-
330
- if (checkIfSnapshotChanged(inst)) {
331
- // Force a re-render.
332
- forceUpdate({
333
- inst: inst
334
- });
335
- }
336
- }, [subscribe, value, getSnapshot]);
337
- useEffect(function () {
338
- // Check for changes right before subscribing. Subsequent changes will be
339
- // detected in the subscription handler.
340
- if (checkIfSnapshotChanged(inst)) {
341
- // Force a re-render.
342
- forceUpdate({
343
- inst: inst
344
- });
345
- }
346
-
347
- var handleStoreChange = function () {
348
- // TODO: Because there is no cross-renderer API for batching updates, it's
349
- // up to the consumer of this library to wrap their subscription event
350
- // with unstable_batchedUpdates. Should we try to detect when this isn't
351
- // the case and print a warning in development?
352
- // The store changed. Check if the snapshot changed since the last time we
353
- // read from the store.
354
- if (checkIfSnapshotChanged(inst)) {
355
- // Force a re-render.
356
- forceUpdate({
357
- inst: inst
358
- });
359
- }
360
- }; // Subscribe to the store and return a clean-up function.
361
-
362
-
363
- return subscribe(handleStoreChange);
364
- }, [subscribe]);
365
- useDebugValue(value);
366
- return value;
367
- }
368
-
369
- function checkIfSnapshotChanged(inst) {
370
- var latestGetSnapshot = inst.getSnapshot;
371
- var prevValue = inst.value;
372
-
373
- try {
374
- var nextValue = latestGetSnapshot();
375
- return !objectIs(prevValue, nextValue);
376
- } catch (error) {
377
- return true;
378
- }
379
- }
380
-
381
- function useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {
382
- // Note: The shim does not use getServerSnapshot, because pre-18 versions of
383
- // React do not expose a way to check if we're hydrating. So users of the shim
384
- // will need to track that themselves and return the correct value
385
- // from `getSnapshot`.
386
- return getSnapshot();
387
- }
388
-
389
- var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');
390
-
391
- var isServerEnvironment = !canUseDOM;
392
-
393
- var shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore;
394
- var useSyncExternalStore$2 = React$1.useSyncExternalStore !== undefined ? React$1.useSyncExternalStore : shim;
395
-
396
- useSyncExternalStoreShim_development.useSyncExternalStore = useSyncExternalStore$2;
397
- /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
398
- if (
399
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
400
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===
401
- 'function'
402
- ) {
403
- __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
404
- }
405
-
406
- })();
407
- }
408
- return useSyncExternalStoreShim_development;
409
- }
410
-
411
- var hasRequiredShim;
412
-
413
- function requireShim () {
414
- if (hasRequiredShim) return shim.exports;
415
- hasRequiredShim = 1;
416
-
417
- if (process.env.NODE_ENV === 'production') {
418
- shim.exports = requireUseSyncExternalStoreShim_production_min();
419
- } else {
420
- shim.exports = requireUseSyncExternalStoreShim_development();
421
- }
422
- return shim.exports;
423
- }
424
-
425
- /**
426
- * @license React
427
- * use-sync-external-store-shim/with-selector.production.min.js
428
- *
429
- * Copyright (c) Facebook, Inc. and its affiliates.
430
- *
431
- * This source code is licensed under the MIT license found in the
432
- * LICENSE file in the root directory of this source tree.
433
- */
434
-
435
- var hasRequiredWithSelector_production_min;
436
-
437
- function requireWithSelector_production_min () {
438
- if (hasRequiredWithSelector_production_min) return withSelector_production_min;
439
- hasRequiredWithSelector_production_min = 1;
440
- var h=React,n=requireShim();function p(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var q="function"===typeof Object.is?Object.is:p,r=n.useSyncExternalStore,t=h.useRef,u=h.useEffect,v=h.useMemo,w=h.useDebugValue;
441
- withSelector_production_min.useSyncExternalStoreWithSelector=function(a,b,e,l,g){var c=t(null);if(null===c.current){var f={hasValue:!1,value:null};c.current=f;}else f=c.current;c=v(function(){function a(a){if(!c){c=!0;d=a;a=l(a);if(void 0!==g&&f.hasValue){var b=f.value;if(g(b,a))return k=b}return k=a}b=k;if(q(d,a))return b;var e=l(a);if(void 0!==g&&g(b,e))return b;d=a;return k=e}var c=!1,d,k,m=void 0===e?null:e;return [function(){return a(b())},null===m?void 0:function(){return a(m())}]},[b,e,l,g]);var d=r(a,c[0],c[1]);
442
- u(function(){f.hasValue=!0;f.value=d;},[d]);w(d);return d};
443
- return withSelector_production_min;
444
- }
445
-
446
- var withSelector_development = {};
447
-
448
- /**
449
- * @license React
450
- * use-sync-external-store-shim/with-selector.development.js
451
- *
452
- * Copyright (c) Facebook, Inc. and its affiliates.
453
- *
454
- * This source code is licensed under the MIT license found in the
455
- * LICENSE file in the root directory of this source tree.
456
- */
457
-
458
- var hasRequiredWithSelector_development;
459
-
460
- function requireWithSelector_development () {
461
- if (hasRequiredWithSelector_development) return withSelector_development;
462
- hasRequiredWithSelector_development = 1;
463
-
464
- if (process.env.NODE_ENV !== "production") {
465
- (function() {
466
-
467
- /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
468
- if (
469
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
470
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===
471
- 'function'
472
- ) {
473
- __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
474
- }
475
- var React$1 = React;
476
- var shim = requireShim();
477
-
478
- /**
479
- * inlined Object.is polyfill to avoid requiring consumers ship their own
480
- * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
481
- */
482
- function is(x, y) {
483
- return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
484
- ;
485
- }
486
-
487
- var objectIs = typeof Object.is === 'function' ? Object.is : is;
488
-
489
- var useSyncExternalStore = shim.useSyncExternalStore;
490
-
491
- // for CommonJS interop.
492
-
493
- var useRef = React$1.useRef,
494
- useEffect = React$1.useEffect,
495
- useMemo = React$1.useMemo,
496
- useDebugValue = React$1.useDebugValue; // Same as useSyncExternalStore, but supports selector and isEqual arguments.
497
-
498
- function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {
499
- // Use this to track the rendered snapshot.
500
- var instRef = useRef(null);
501
- var inst;
502
-
503
- if (instRef.current === null) {
504
- inst = {
505
- hasValue: false,
506
- value: null
507
- };
508
- instRef.current = inst;
509
- } else {
510
- inst = instRef.current;
511
- }
512
-
513
- var _useMemo = useMemo(function () {
514
- // Track the memoized state using closure variables that are local to this
515
- // memoized instance of a getSnapshot function. Intentionally not using a
516
- // useRef hook, because that state would be shared across all concurrent
517
- // copies of the hook/component.
518
- var hasMemo = false;
519
- var memoizedSnapshot;
520
- var memoizedSelection;
521
-
522
- var memoizedSelector = function (nextSnapshot) {
523
- if (!hasMemo) {
524
- // The first time the hook is called, there is no memoized result.
525
- hasMemo = true;
526
- memoizedSnapshot = nextSnapshot;
527
-
528
- var _nextSelection = selector(nextSnapshot);
529
-
530
- if (isEqual !== undefined) {
531
- // Even if the selector has changed, the currently rendered selection
532
- // may be equal to the new selection. We should attempt to reuse the
533
- // current value if possible, to preserve downstream memoizations.
534
- if (inst.hasValue) {
535
- var currentSelection = inst.value;
536
-
537
- if (isEqual(currentSelection, _nextSelection)) {
538
- memoizedSelection = currentSelection;
539
- return currentSelection;
540
- }
541
- }
542
- }
543
-
544
- memoizedSelection = _nextSelection;
545
- return _nextSelection;
546
- } // We may be able to reuse the previous invocation's result.
547
-
548
-
549
- // We may be able to reuse the previous invocation's result.
550
- var prevSnapshot = memoizedSnapshot;
551
- var prevSelection = memoizedSelection;
552
-
553
- if (objectIs(prevSnapshot, nextSnapshot)) {
554
- // The snapshot is the same as last time. Reuse the previous selection.
555
- return prevSelection;
556
- } // The snapshot has changed, so we need to compute a new selection.
557
-
558
-
559
- // The snapshot has changed, so we need to compute a new selection.
560
- var nextSelection = selector(nextSnapshot); // If a custom isEqual function is provided, use that to check if the data
561
- // has changed. If it hasn't, return the previous selection. That signals
562
- // to React that the selections are conceptually equal, and we can bail
563
- // out of rendering.
564
-
565
- // If a custom isEqual function is provided, use that to check if the data
566
- // has changed. If it hasn't, return the previous selection. That signals
567
- // to React that the selections are conceptually equal, and we can bail
568
- // out of rendering.
569
- if (isEqual !== undefined && isEqual(prevSelection, nextSelection)) {
570
- return prevSelection;
571
- }
572
-
573
- memoizedSnapshot = nextSnapshot;
574
- memoizedSelection = nextSelection;
575
- return nextSelection;
576
- }; // Assigning this to a constant so that Flow knows it can't change.
577
-
578
-
579
- // Assigning this to a constant so that Flow knows it can't change.
580
- var maybeGetServerSnapshot = getServerSnapshot === undefined ? null : getServerSnapshot;
581
-
582
- var getSnapshotWithSelector = function () {
583
- return memoizedSelector(getSnapshot());
584
- };
585
-
586
- var getServerSnapshotWithSelector = maybeGetServerSnapshot === null ? undefined : function () {
587
- return memoizedSelector(maybeGetServerSnapshot());
588
- };
589
- return [getSnapshotWithSelector, getServerSnapshotWithSelector];
590
- }, [getSnapshot, getServerSnapshot, selector, isEqual]),
591
- getSelection = _useMemo[0],
592
- getServerSelection = _useMemo[1];
593
-
594
- var value = useSyncExternalStore(subscribe, getSelection, getServerSelection);
595
- useEffect(function () {
596
- inst.hasValue = true;
597
- inst.value = value;
598
- }, [value]);
599
- useDebugValue(value);
600
- return value;
601
- }
602
-
603
- withSelector_development.useSyncExternalStoreWithSelector = useSyncExternalStoreWithSelector;
604
- /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
605
- if (
606
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
607
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===
608
- 'function'
609
- ) {
610
- __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
611
- }
612
-
613
- })();
614
- }
615
- return withSelector_development;
616
- }
617
-
618
- if (process.env.NODE_ENV === 'production') {
619
- withSelector.exports = requireWithSelector_production_min();
620
- } else {
621
- withSelector.exports = requireWithSelector_development();
622
- }
623
-
624
- var withSelectorExports = withSelector.exports;
625
-
626
- /**
627
- * To synchronize the editor instance with the component state,
628
- * we need to create a separate instance that is not affected by the component re-renders.
629
- */
630
- function makeEditorStateInstance(initialEditor) {
631
- let transactionNumber = 0;
632
- let lastTransactionNumber = 0;
633
- let lastSnapshot = { editor: initialEditor, transactionNumber: 0 };
634
- let editor = initialEditor;
635
- const subscribers = new Set();
636
- const editorInstance = {
637
- /**
638
- * Get the current editor instance.
639
- */
640
- getSnapshot() {
641
- if (transactionNumber === lastTransactionNumber) {
642
- return lastSnapshot;
643
- }
644
- lastTransactionNumber = transactionNumber;
645
- lastSnapshot = { editor, transactionNumber };
646
- return lastSnapshot;
647
- },
648
- /**
649
- * Always disable the editor on the server-side.
650
- */
651
- getServerSnapshot() {
652
- return { editor: null, transactionNumber: 0 };
653
- },
654
- /**
655
- * Subscribe to the editor instance's changes.
656
- */
657
- subscribe(callback) {
658
- subscribers.add(callback);
659
- return () => {
660
- subscribers.delete(callback);
661
- };
662
- },
663
- /**
664
- * Watch the editor instance for changes.
665
- */
666
- watch(nextEditor) {
667
- editor = nextEditor;
668
- if (editor) {
669
- /**
670
- * This will force a re-render when the editor state changes.
671
- * This is to support things like `editor.can().toggleBold()` in components that `useEditor`.
672
- * This could be more efficient, but it's a good trade-off for now.
673
- */
674
- const fn = () => {
675
- transactionNumber += 1;
676
- subscribers.forEach(callback => callback());
677
- };
678
- const currentEditor = editor;
679
- currentEditor.on('transaction', fn);
680
- return () => {
681
- currentEditor.off('transaction', fn);
682
- };
683
- }
684
- },
248
+ this.lastTransactionNumber = this.transactionNumber;
249
+ this.lastSnapshot = { editor: this.editor, transactionNumber: this.transactionNumber };
250
+ return this.lastSnapshot;
251
+ }
252
+ /**
253
+ * Always disable the editor on the server-side.
254
+ */
255
+ getServerSnapshot() {
256
+ return { editor: null, transactionNumber: 0 };
257
+ }
258
+ /**
259
+ * Subscribe to the editor instance's changes.
260
+ */
261
+ subscribe(callback) {
262
+ this.subscribers.add(callback);
263
+ return () => {
264
+ this.subscribers.delete(callback);
685
265
  };
686
- return editorInstance;
687
- }
266
+ }
267
+ /**
268
+ * Watch the editor instance for changes.
269
+ */
270
+ watch(nextEditor) {
271
+ this.editor = nextEditor;
272
+ if (this.editor) {
273
+ const fn = () => {
274
+ this.transactionNumber += 1;
275
+ this.subscribers.forEach((callback) => callback());
276
+ };
277
+ const currentEditor = this.editor;
278
+ currentEditor.on("transaction", fn);
279
+ return () => {
280
+ currentEditor.off("transaction", fn);
281
+ };
282
+ }
283
+ return void 0;
284
+ }
285
+ };
688
286
  function useEditorState(options) {
689
- const [editorInstance] = React.useState(() => makeEditorStateInstance(options.editor));
690
- // Using the `useSyncExternalStore` hook to sync the editor instance with the component state
691
- const selectedState = withSelectorExports.useSyncExternalStoreWithSelector(editorInstance.subscribe, editorInstance.getSnapshot, editorInstance.getServerSnapshot, options.selector, options.equalityFn);
692
- React.useEffect(() => {
693
- return editorInstance.watch(options.editor);
694
- }, [options.editor]);
695
- React.useDebugValue(selectedState);
696
- return selectedState;
287
+ var _a;
288
+ const [editorStateManager] = (0, import_react3.useState)(() => new EditorStateManager(options.editor));
289
+ const selectedState = (0, import_with_selector.useSyncExternalStoreWithSelector)(
290
+ editorStateManager.subscribe,
291
+ editorStateManager.getSnapshot,
292
+ editorStateManager.getServerSnapshot,
293
+ options.selector,
294
+ (_a = options.equalityFn) != null ? _a : import_react2.default
295
+ );
296
+ useIsomorphicLayoutEffect(() => {
297
+ return editorStateManager.watch(options.editor);
298
+ }, [options.editor, editorStateManager]);
299
+ (0, import_react3.useDebugValue)(selectedState);
300
+ return selectedState;
697
301
  }
698
302
 
699
- const isDev = process.env.NODE_ENV !== 'production';
700
- const isSSR = typeof window === 'undefined';
701
- const isNext = isSSR || Boolean(typeof window !== 'undefined' && window.next);
702
- function useEditor(options = {}, deps = []) {
703
- const isMounted = React.useRef(false);
704
- const [editor, setEditor] = React.useState(() => {
705
- if (options.immediatelyRender === undefined) {
706
- if (isSSR || isNext) {
707
- // TODO in the next major release, we should throw an error here
708
- if (isDev) {
709
- /**
710
- * Throw an error in development, to make sure the developer is aware that tiptap cannot be SSR'd
711
- * and that they need to set `immediatelyRender` to `false` to avoid hydration mismatches.
712
- */
713
- console.warn('Tiptap Error: SSR has been detected, please set `immediatelyRender` explicitly to `false` to avoid hydration mismatches.');
714
- }
715
- // Best faith effort in production, run the code in the legacy mode to avoid hydration mismatches and errors in production
716
- return null;
717
- }
718
- // Default to immediately rendering when client-side rendering
719
- return new Editor(options);
720
- }
721
- if (options.immediatelyRender && isSSR && isDev) {
722
- // Warn in development, to make sure the developer is aware that tiptap cannot be SSR'd, set `immediatelyRender` to `false` to avoid hydration mismatches.
723
- throw new Error('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.');
724
- }
725
- if (options.immediatelyRender) {
726
- return new Editor(options);
727
- }
728
- return null;
729
- });
730
- React.useDebugValue(editor);
731
- // This effect will handle creating/updating the editor instance
732
- React.useEffect(() => {
733
- let editorInstance = editor;
734
- if (!editorInstance) {
735
- editorInstance = new Editor(options);
736
- // instantiate the editor if it doesn't exist
737
- // for ssr, this is the first time the editor is created
738
- setEditor(editorInstance);
739
- }
740
- else {
741
- // if the editor does exist, update the editor options accordingly
742
- editorInstance.setOptions(options);
743
- }
744
- }, deps);
745
- const { onBeforeCreate, onBlur, onCreate, onDestroy, onFocus, onSelectionUpdate, onTransaction, onUpdate, onContentError, } = options;
746
- const onBeforeCreateRef = React.useRef(onBeforeCreate);
747
- const onBlurRef = React.useRef(onBlur);
748
- const onCreateRef = React.useRef(onCreate);
749
- const onDestroyRef = React.useRef(onDestroy);
750
- const onFocusRef = React.useRef(onFocus);
751
- const onSelectionUpdateRef = React.useRef(onSelectionUpdate);
752
- const onTransactionRef = React.useRef(onTransaction);
753
- const onUpdateRef = React.useRef(onUpdate);
754
- const onContentErrorRef = React.useRef(onContentError);
755
- // This effect will handle updating the editor instance
756
- // when the event handlers change.
757
- React.useEffect(() => {
758
- if (!editor) {
759
- return;
760
- }
761
- if (onBeforeCreate) {
762
- editor.off('beforeCreate', onBeforeCreateRef.current);
763
- editor.on('beforeCreate', onBeforeCreate);
764
- onBeforeCreateRef.current = onBeforeCreate;
765
- }
766
- if (onBlur) {
767
- editor.off('blur', onBlurRef.current);
768
- editor.on('blur', onBlur);
769
- onBlurRef.current = onBlur;
770
- }
771
- if (onCreate) {
772
- editor.off('create', onCreateRef.current);
773
- editor.on('create', onCreate);
774
- onCreateRef.current = onCreate;
775
- }
776
- if (onDestroy) {
777
- editor.off('destroy', onDestroyRef.current);
778
- editor.on('destroy', onDestroy);
779
- onDestroyRef.current = onDestroy;
780
- }
781
- if (onFocus) {
782
- editor.off('focus', onFocusRef.current);
783
- editor.on('focus', onFocus);
784
- onFocusRef.current = onFocus;
785
- }
786
- if (onSelectionUpdate) {
787
- editor.off('selectionUpdate', onSelectionUpdateRef.current);
788
- editor.on('selectionUpdate', onSelectionUpdate);
789
- onSelectionUpdateRef.current = onSelectionUpdate;
790
- }
791
- if (onTransaction) {
792
- editor.off('transaction', onTransactionRef.current);
793
- editor.on('transaction', onTransaction);
794
- onTransactionRef.current = onTransaction;
795
- }
796
- if (onUpdate) {
797
- editor.off('update', onUpdateRef.current);
798
- editor.on('update', onUpdate);
799
- onUpdateRef.current = onUpdate;
800
- }
801
- if (onContentError) {
802
- editor.off('contentError', onContentErrorRef.current);
803
- editor.on('contentError', onContentError);
804
- onContentErrorRef.current = onContentError;
805
- }
806
- }, [
807
- onBeforeCreate,
808
- onBlur,
809
- onCreate,
810
- onDestroy,
811
- onFocus,
812
- onSelectionUpdate,
813
- onTransaction,
814
- onUpdate,
815
- onContentError,
816
- editor,
817
- ]);
303
+ // src/useEditor.ts
304
+ var isDev = process.env.NODE_ENV !== "production";
305
+ var isSSR = typeof window === "undefined";
306
+ var isNext = isSSR || Boolean(typeof window !== "undefined" && window.next);
307
+ var EditorInstanceManager = class _EditorInstanceManager {
308
+ constructor(options) {
818
309
  /**
819
- * Destroy the editor instance when the component completely unmounts
820
- * As opposed to the cleanup function in the effect above, this will
821
- * only be called when the component is removed from the DOM, since it has no deps.
822
- * */
823
- React.useEffect(() => {
824
- isMounted.current = true;
825
- return () => {
826
- isMounted.current = false;
827
- if (editor) {
828
- // We need to destroy the editor asynchronously to avoid memory leaks
829
- // because the editor instance is still being used in the component.
830
- setTimeout(() => {
831
- // re-use the editor instance if it hasn't been destroyed yet
832
- // and the component is still mounted
833
- // otherwise, asynchronously destroy the editor instance
834
- if (!isMounted.current && !editor.isDestroyed) {
835
- editor.destroy();
836
- }
837
- });
838
- }
839
- };
840
- }, []);
841
- // The default behavior is to re-render on each transaction
842
- // This is legacy behavior that will be removed in future versions
843
- useEditorState({
844
- editor,
845
- selector: ({ transactionNumber }) => {
846
- if (options.shouldRerenderOnTransaction === false) {
847
- // This will prevent the editor from re-rendering on each transaction
848
- return null;
849
- }
850
- // This will avoid re-rendering on the first transaction when `immediatelyRender` is set to `true`
851
- if (options.immediatelyRender && transactionNumber === 0) {
852
- return 0;
853
- }
854
- return transactionNumber + 1;
855
- },
856
- });
857
- return editor;
858
- }
859
-
860
- const EditorContext = React.createContext({
861
- editor: null,
862
- });
863
- const EditorConsumer = EditorContext.Consumer;
864
- /**
865
- * A hook to get the current editor instance.
866
- */
867
- const useCurrentEditor = () => React.useContext(EditorContext);
868
- /**
869
- * This is the provider component for the editor.
870
- * It allows the editor to be accessible across the entire component tree
871
- * with `useCurrentEditor`.
872
- */
873
- function EditorProvider({ children, slotAfter, slotBefore, ...editorOptions }) {
874
- const editor = useEditor(editorOptions);
875
- if (!editor) {
310
+ * The current editor instance.
311
+ */
312
+ this.editor = null;
313
+ /**
314
+ * The subscriptions to notify when the editor instance
315
+ * has been created or destroyed.
316
+ */
317
+ this.subscriptions = /* @__PURE__ */ new Set();
318
+ /**
319
+ * Whether the editor has been mounted.
320
+ */
321
+ this.isComponentMounted = false;
322
+ /**
323
+ * The most recent dependencies array.
324
+ */
325
+ this.previousDeps = null;
326
+ /**
327
+ * The unique instance ID. This is used to identify the editor instance. And will be re-generated for each new instance.
328
+ */
329
+ this.instanceId = "";
330
+ this.options = options;
331
+ this.subscriptions = /* @__PURE__ */ new Set();
332
+ this.setEditor(this.getInitialEditor());
333
+ this.scheduleDestroy();
334
+ this.getEditor = this.getEditor.bind(this);
335
+ this.getServerSnapshot = this.getServerSnapshot.bind(this);
336
+ this.subscribe = this.subscribe.bind(this);
337
+ this.refreshEditorInstance = this.refreshEditorInstance.bind(this);
338
+ this.scheduleDestroy = this.scheduleDestroy.bind(this);
339
+ this.onRender = this.onRender.bind(this);
340
+ this.createEditor = this.createEditor.bind(this);
341
+ }
342
+ setEditor(editor) {
343
+ this.editor = editor;
344
+ this.instanceId = Math.random().toString(36).slice(2, 9);
345
+ this.subscriptions.forEach((cb) => cb());
346
+ }
347
+ getInitialEditor() {
348
+ if (this.options.current.immediatelyRender === void 0) {
349
+ if (isSSR || isNext) {
350
+ if (isDev) {
351
+ throw new Error(
352
+ "Tiptap Error: SSR has been detected, please set `immediatelyRender` explicitly to `false` to avoid hydration mismatches."
353
+ );
354
+ }
876
355
  return null;
356
+ }
357
+ return this.createEditor();
877
358
  }
878
- return (React.createElement(EditorContext.Provider, { value: { editor } },
879
- slotBefore,
880
- React.createElement(EditorConsumer, null, ({ editor: currentEditor }) => (React.createElement(EditorContent, { editor: currentEditor }))),
881
- children,
882
- slotAfter));
883
- }
884
-
885
- const BubbleMenu = (props) => {
886
- const [element, setElement] = React.useState(null);
887
- const { editor: currentEditor } = useCurrentEditor();
888
- React.useEffect(() => {
889
- var _a;
890
- if (!element) {
891
- return;
892
- }
893
- if (((_a = props.editor) === null || _a === void 0 ? void 0 : _a.isDestroyed) || (currentEditor === null || currentEditor === void 0 ? void 0 : currentEditor.isDestroyed)) {
894
- return;
895
- }
896
- const { pluginKey = 'bubbleMenu', editor, tippyOptions = {}, updateDelay, shouldShow = null, } = props;
897
- const menuEditor = editor || currentEditor;
898
- if (!menuEditor) {
899
- console.warn('BubbleMenu component is not rendered inside of an editor component or does not have editor prop.');
900
- return;
359
+ if (this.options.current.immediatelyRender && isSSR && isDev) {
360
+ throw new Error(
361
+ "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."
362
+ );
363
+ }
364
+ if (this.options.current.immediatelyRender) {
365
+ return this.createEditor();
366
+ }
367
+ return null;
368
+ }
369
+ /**
370
+ * Create a new editor instance. And attach event listeners.
371
+ */
372
+ createEditor() {
373
+ const optionsToApply = {
374
+ ...this.options.current,
375
+ // Always call the most recent version of the callback function by default
376
+ onBeforeCreate: (...args) => {
377
+ var _a, _b;
378
+ return (_b = (_a = this.options.current).onBeforeCreate) == null ? void 0 : _b.call(_a, ...args);
379
+ },
380
+ onBlur: (...args) => {
381
+ var _a, _b;
382
+ return (_b = (_a = this.options.current).onBlur) == null ? void 0 : _b.call(_a, ...args);
383
+ },
384
+ onCreate: (...args) => {
385
+ var _a, _b;
386
+ return (_b = (_a = this.options.current).onCreate) == null ? void 0 : _b.call(_a, ...args);
387
+ },
388
+ onDestroy: (...args) => {
389
+ var _a, _b;
390
+ return (_b = (_a = this.options.current).onDestroy) == null ? void 0 : _b.call(_a, ...args);
391
+ },
392
+ onFocus: (...args) => {
393
+ var _a, _b;
394
+ return (_b = (_a = this.options.current).onFocus) == null ? void 0 : _b.call(_a, ...args);
395
+ },
396
+ onSelectionUpdate: (...args) => {
397
+ var _a, _b;
398
+ return (_b = (_a = this.options.current).onSelectionUpdate) == null ? void 0 : _b.call(_a, ...args);
399
+ },
400
+ onTransaction: (...args) => {
401
+ var _a, _b;
402
+ return (_b = (_a = this.options.current).onTransaction) == null ? void 0 : _b.call(_a, ...args);
403
+ },
404
+ onUpdate: (...args) => {
405
+ var _a, _b;
406
+ return (_b = (_a = this.options.current).onUpdate) == null ? void 0 : _b.call(_a, ...args);
407
+ },
408
+ onContentError: (...args) => {
409
+ var _a, _b;
410
+ return (_b = (_a = this.options.current).onContentError) == null ? void 0 : _b.call(_a, ...args);
411
+ },
412
+ onDrop: (...args) => {
413
+ var _a, _b;
414
+ return (_b = (_a = this.options.current).onDrop) == null ? void 0 : _b.call(_a, ...args);
415
+ },
416
+ onPaste: (...args) => {
417
+ var _a, _b;
418
+ return (_b = (_a = this.options.current).onPaste) == null ? void 0 : _b.call(_a, ...args);
419
+ },
420
+ onDelete: (...args) => {
421
+ var _a, _b;
422
+ return (_b = (_a = this.options.current).onDelete) == null ? void 0 : _b.call(_a, ...args);
423
+ }
424
+ };
425
+ const editor = new import_core.Editor(optionsToApply);
426
+ return editor;
427
+ }
428
+ /**
429
+ * Get the current editor instance.
430
+ */
431
+ getEditor() {
432
+ return this.editor;
433
+ }
434
+ /**
435
+ * Always disable the editor on the server-side.
436
+ */
437
+ getServerSnapshot() {
438
+ return null;
439
+ }
440
+ /**
441
+ * Subscribe to the editor instance's changes.
442
+ */
443
+ subscribe(onStoreChange) {
444
+ this.subscriptions.add(onStoreChange);
445
+ return () => {
446
+ this.subscriptions.delete(onStoreChange);
447
+ };
448
+ }
449
+ static compareOptions(a, b) {
450
+ return Object.keys(a).every((key) => {
451
+ if ([
452
+ "onCreate",
453
+ "onBeforeCreate",
454
+ "onDestroy",
455
+ "onUpdate",
456
+ "onTransaction",
457
+ "onFocus",
458
+ "onBlur",
459
+ "onSelectionUpdate",
460
+ "onContentError",
461
+ "onDrop",
462
+ "onPaste"
463
+ ].includes(key)) {
464
+ return true;
465
+ }
466
+ if (key === "extensions" && a.extensions && b.extensions) {
467
+ if (a.extensions.length !== b.extensions.length) {
468
+ return false;
901
469
  }
902
- const plugin = extensionBubbleMenu.BubbleMenuPlugin({
903
- updateDelay,
904
- editor: menuEditor,
905
- element,
906
- pluginKey,
907
- shouldShow,
908
- tippyOptions,
470
+ return a.extensions.every((extension, index) => {
471
+ var _a;
472
+ if (extension !== ((_a = b.extensions) == null ? void 0 : _a[index])) {
473
+ return false;
474
+ }
475
+ return true;
909
476
  });
910
- menuEditor.registerPlugin(plugin);
911
- return () => menuEditor.unregisterPlugin(pluginKey);
912
- }, [props.editor, currentEditor, element]);
913
- return (React.createElement("div", { ref: setElement, className: props.className, style: { visibility: 'hidden' } }, props.children));
914
- };
915
-
916
- const FloatingMenu = (props) => {
917
- const [element, setElement] = React.useState(null);
918
- const { editor: currentEditor } = useCurrentEditor();
919
- React.useEffect(() => {
920
- var _a;
921
- if (!element) {
922
- return;
477
+ }
478
+ if (a[key] !== b[key]) {
479
+ return false;
480
+ }
481
+ return true;
482
+ });
483
+ }
484
+ /**
485
+ * On each render, we will create, update, or destroy the editor instance.
486
+ * @param deps The dependencies to watch for changes
487
+ * @returns A cleanup function
488
+ */
489
+ onRender(deps) {
490
+ return () => {
491
+ this.isComponentMounted = true;
492
+ clearTimeout(this.scheduledDestructionTimeout);
493
+ if (this.editor && !this.editor.isDestroyed && deps.length === 0) {
494
+ if (!_EditorInstanceManager.compareOptions(this.options.current, this.editor.options)) {
495
+ this.editor.setOptions({
496
+ ...this.options.current,
497
+ editable: this.editor.isEditable
498
+ });
923
499
  }
924
- if (((_a = props.editor) === null || _a === void 0 ? void 0 : _a.isDestroyed) || (currentEditor === null || currentEditor === void 0 ? void 0 : currentEditor.isDestroyed)) {
925
- return;
500
+ } else {
501
+ this.refreshEditorInstance(deps);
502
+ }
503
+ return () => {
504
+ this.isComponentMounted = false;
505
+ this.scheduleDestroy();
506
+ };
507
+ };
508
+ }
509
+ /**
510
+ * Recreate the editor instance if the dependencies have changed.
511
+ */
512
+ refreshEditorInstance(deps) {
513
+ if (this.editor && !this.editor.isDestroyed) {
514
+ if (this.previousDeps === null) {
515
+ this.previousDeps = deps;
516
+ return;
517
+ }
518
+ const depsAreEqual = this.previousDeps.length === deps.length && this.previousDeps.every((dep, index) => dep === deps[index]);
519
+ if (depsAreEqual) {
520
+ return;
521
+ }
522
+ }
523
+ if (this.editor && !this.editor.isDestroyed) {
524
+ this.editor.destroy();
525
+ }
526
+ this.setEditor(this.createEditor());
527
+ this.previousDeps = deps;
528
+ }
529
+ /**
530
+ * Schedule the destruction of the editor instance.
531
+ * This will only destroy the editor if it was not mounted on the next tick.
532
+ * This is to avoid destroying the editor instance when it's actually still mounted.
533
+ */
534
+ scheduleDestroy() {
535
+ const currentInstanceId = this.instanceId;
536
+ const currentEditor = this.editor;
537
+ this.scheduledDestructionTimeout = setTimeout(() => {
538
+ if (this.isComponentMounted && this.instanceId === currentInstanceId) {
539
+ if (currentEditor) {
540
+ currentEditor.setOptions(this.options.current);
926
541
  }
927
- const { pluginKey = 'floatingMenu', editor, tippyOptions = {}, shouldShow = null, } = props;
928
- const menuEditor = editor || currentEditor;
929
- if (!menuEditor) {
930
- console.warn('FloatingMenu component is not rendered inside of an editor component or does not have editor prop.');
931
- return;
542
+ return;
543
+ }
544
+ if (currentEditor && !currentEditor.isDestroyed) {
545
+ currentEditor.destroy();
546
+ if (this.instanceId === currentInstanceId) {
547
+ this.setEditor(null);
932
548
  }
933
- const plugin = extensionFloatingMenu.FloatingMenuPlugin({
934
- pluginKey,
935
- editor: menuEditor,
936
- element,
937
- tippyOptions,
938
- shouldShow,
939
- });
940
- menuEditor.registerPlugin(plugin);
941
- return () => menuEditor.unregisterPlugin(pluginKey);
942
- }, [
943
- props.editor,
944
- currentEditor,
945
- element,
946
- ]);
947
- return (React.createElement("div", { ref: setElement, className: props.className, style: { visibility: 'hidden' } }, props.children));
549
+ }
550
+ }, 1);
551
+ }
948
552
  };
553
+ function useEditor(options = {}, deps = []) {
554
+ const mostRecentOptions = (0, import_react4.useRef)(options);
555
+ mostRecentOptions.current = options;
556
+ const [instanceManager] = (0, import_react4.useState)(() => new EditorInstanceManager(mostRecentOptions));
557
+ const editor = (0, import_shim2.useSyncExternalStore)(
558
+ instanceManager.subscribe,
559
+ instanceManager.getEditor,
560
+ instanceManager.getServerSnapshot
561
+ );
562
+ (0, import_react4.useDebugValue)(editor);
563
+ (0, import_react4.useEffect)(instanceManager.onRender(deps));
564
+ useEditorState({
565
+ editor,
566
+ selector: ({ transactionNumber }) => {
567
+ if (options.shouldRerenderOnTransaction === false || options.shouldRerenderOnTransaction === void 0) {
568
+ return null;
569
+ }
570
+ if (options.immediatelyRender && transactionNumber === 0) {
571
+ return 0;
572
+ }
573
+ return transactionNumber + 1;
574
+ }
575
+ });
576
+ return editor;
577
+ }
949
578
 
950
- const ReactNodeViewContext = React.createContext({
951
- onDragStart: undefined,
579
+ // src/Context.tsx
580
+ var import_jsx_runtime2 = require("react/jsx-runtime");
581
+ var EditorContext = (0, import_react5.createContext)({
582
+ editor: null
952
583
  });
953
- const useReactNodeView = () => React.useContext(ReactNodeViewContext);
584
+ var EditorConsumer = EditorContext.Consumer;
585
+ var useCurrentEditor = () => (0, import_react5.useContext)(EditorContext);
586
+ function EditorProvider({
587
+ children,
588
+ slotAfter,
589
+ slotBefore,
590
+ editorContainerProps = {},
591
+ ...editorOptions
592
+ }) {
593
+ const editor = useEditor(editorOptions);
594
+ const contextValue = (0, import_react5.useMemo)(() => ({ editor }), [editor]);
595
+ if (!editor) {
596
+ return null;
597
+ }
598
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(EditorContext.Provider, { value: contextValue, children: [
599
+ slotBefore,
600
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(EditorConsumer, { children: ({ editor: currentEditor }) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(EditorContent, { editor: currentEditor, ...editorContainerProps }) }),
601
+ children,
602
+ slotAfter
603
+ ] });
604
+ }
954
605
 
955
- const NodeViewContent = props => {
956
- const Tag = props.as || 'div';
957
- const { nodeViewContentRef } = useReactNodeView();
958
- return (React.createElement(Tag, { ...props, ref: nodeViewContentRef, "data-node-view-content": "", style: {
959
- whiteSpace: 'pre-wrap',
960
- ...props.style,
961
- } }));
606
+ // src/useReactNodeView.ts
607
+ var import_react6 = require("react");
608
+ var ReactNodeViewContext = (0, import_react6.createContext)({
609
+ onDragStart: () => {
610
+ },
611
+ nodeViewContentChildren: void 0,
612
+ nodeViewContentRef: () => {
613
+ }
614
+ });
615
+ var ReactNodeViewContentProvider = ({ children, content }) => {
616
+ return (0, import_react6.createElement)(ReactNodeViewContext.Provider, { value: { nodeViewContentChildren: content } }, children);
962
617
  };
618
+ var useReactNodeView = () => (0, import_react6.useContext)(ReactNodeViewContext);
619
+
620
+ // src/NodeViewContent.tsx
621
+ var import_jsx_runtime3 = (
622
+ // @ts-ignore
623
+ require("react/jsx-runtime")
624
+ );
625
+ function NodeViewContent({
626
+ as: Tag = "div",
627
+ ...props
628
+ }) {
629
+ const { nodeViewContentRef, nodeViewContentChildren } = useReactNodeView();
630
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
631
+ Tag,
632
+ {
633
+ ...props,
634
+ ref: nodeViewContentRef,
635
+ "data-node-view-content": "",
636
+ style: {
637
+ whiteSpace: "pre-wrap",
638
+ ...props.style
639
+ },
640
+ children: nodeViewContentChildren
641
+ }
642
+ );
643
+ }
963
644
 
964
- const NodeViewWrapper = React.forwardRef((props, ref) => {
965
- const { onDragStart } = useReactNodeView();
966
- const Tag = props.as || 'div';
967
- return (React.createElement(Tag, { ...props, ref: ref, "data-node-view-wrapper": "", onDragStart: onDragStart, style: {
968
- whiteSpace: 'normal',
969
- ...props.style,
970
- } }));
645
+ // src/NodeViewWrapper.tsx
646
+ var import_react7 = __toESM(require("react"), 1);
647
+ var import_jsx_runtime4 = (
648
+ // @ts-ignore
649
+ require("react/jsx-runtime")
650
+ );
651
+ var NodeViewWrapper = import_react7.default.forwardRef((props, ref) => {
652
+ const { onDragStart } = useReactNodeView();
653
+ const Tag = props.as || "div";
654
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
655
+ Tag,
656
+ {
657
+ ...props,
658
+ ref,
659
+ "data-node-view-wrapper": "",
660
+ onDragStart,
661
+ style: {
662
+ whiteSpace: "normal",
663
+ ...props.style
664
+ }
665
+ }
666
+ );
971
667
  });
972
668
 
973
- /**
974
- * Check if a component is a class component.
975
- * @param Component
976
- * @returns {boolean}
977
- */
669
+ // src/ReactMarkViewRenderer.tsx
670
+ var import_core2 = require("@tiptap/core");
671
+ var import_react9 = __toESM(require("react"), 1);
672
+
673
+ // src/ReactRenderer.tsx
674
+ var import_react8 = require("react");
675
+ var import_react_dom2 = require("react-dom");
676
+ var import_jsx_runtime5 = require("react/jsx-runtime");
978
677
  function isClassComponent(Component) {
979
- return !!(typeof Component === 'function'
980
- && Component.prototype
981
- && Component.prototype.isReactComponent);
678
+ return !!(typeof Component === "function" && Component.prototype && Component.prototype.isReactComponent);
982
679
  }
983
- /**
984
- * Check if a component is a forward ref component.
985
- * @param Component
986
- * @returns {boolean}
987
- */
988
680
  function isForwardRefComponent(Component) {
989
- var _a;
990
- return !!(typeof Component === 'object'
991
- && ((_a = Component.$$typeof) === null || _a === void 0 ? void 0 : _a.toString()) === 'Symbol(react.forward_ref)');
681
+ return !!(typeof Component === "object" && Component.$$typeof && (Component.$$typeof.toString() === "Symbol(react.forward_ref)" || Component.$$typeof.description === "react.forward_ref"));
992
682
  }
993
- /**
994
- * The ReactRenderer class. It's responsible for rendering React components inside the editor.
995
- * @example
996
- * new ReactRenderer(MyComponent, {
997
- * editor,
998
- * props: {
999
- * foo: 'bar',
1000
- * },
1001
- * as: 'span',
1002
- * })
1003
- */
1004
- class ReactRenderer {
1005
- constructor(component, { editor, props = {}, as = 'div', className = '', attrs, }) {
1006
- this.ref = null;
1007
- this.id = Math.floor(Math.random() * 0xFFFFFFFF).toString();
1008
- this.component = component;
1009
- this.editor = editor;
1010
- this.props = props;
1011
- this.element = document.createElement(as);
1012
- this.element.classList.add('react-renderer');
1013
- if (className) {
1014
- this.element.classList.add(...className.split(' '));
1015
- }
1016
- if (attrs) {
1017
- Object.keys(attrs).forEach(key => {
1018
- this.element.setAttribute(key, attrs[key]);
1019
- });
1020
- }
1021
- this.render();
683
+ function isMemoComponent(Component) {
684
+ return !!(typeof Component === "object" && Component.$$typeof && (Component.$$typeof.toString() === "Symbol(react.memo)" || Component.$$typeof.description === "react.memo"));
685
+ }
686
+ function canReceiveRef(Component) {
687
+ if (isClassComponent(Component)) {
688
+ return true;
689
+ }
690
+ if (isForwardRefComponent(Component)) {
691
+ return true;
692
+ }
693
+ if (isMemoComponent(Component)) {
694
+ const wrappedComponent = Component.type;
695
+ if (wrappedComponent) {
696
+ return isClassComponent(wrappedComponent) || isForwardRefComponent(wrappedComponent);
1022
697
  }
1023
- render() {
1024
- var _a, _b;
1025
- const Component = this.component;
1026
- const props = this.props;
1027
- if (isClassComponent(Component) || isForwardRefComponent(Component)) {
1028
- props.ref = (ref) => {
1029
- this.ref = ref;
1030
- };
1031
- }
1032
- this.reactElement = React.createElement(Component, { ...props });
1033
- (_b = (_a = this.editor) === null || _a === void 0 ? void 0 : _a.contentComponent) === null || _b === void 0 ? void 0 : _b.setRenderer(this.id, this);
698
+ }
699
+ return false;
700
+ }
701
+ function isReact19Plus() {
702
+ try {
703
+ if (import_react8.version) {
704
+ const majorVersion = parseInt(import_react8.version.split(".")[0], 10);
705
+ return majorVersion >= 19;
1034
706
  }
1035
- updateProps(props = {}) {
1036
- this.props = {
1037
- ...this.props,
1038
- ...props,
1039
- };
707
+ } catch {
708
+ }
709
+ return false;
710
+ }
711
+ var ReactRenderer = class {
712
+ /**
713
+ * Immediately creates element and renders the provided React component.
714
+ */
715
+ constructor(component, { editor, props = {}, as = "div", className = "" }) {
716
+ this.ref = null;
717
+ this.id = Math.floor(Math.random() * 4294967295).toString();
718
+ this.component = component;
719
+ this.editor = editor;
720
+ this.props = props;
721
+ this.element = document.createElement(as);
722
+ this.element.classList.add("react-renderer");
723
+ if (className) {
724
+ this.element.classList.add(...className.split(" "));
725
+ }
726
+ if (this.editor.isInitialized) {
727
+ (0, import_react_dom2.flushSync)(() => {
728
+ this.render();
729
+ });
730
+ } else {
731
+ queueMicrotask(() => {
1040
732
  this.render();
733
+ });
1041
734
  }
1042
- destroy() {
1043
- var _a, _b;
1044
- (_b = (_a = this.editor) === null || _a === void 0 ? void 0 : _a.contentComponent) === null || _b === void 0 ? void 0 : _b.removeRenderer(this.id);
735
+ }
736
+ /**
737
+ * Render the React component.
738
+ */
739
+ render() {
740
+ var _a;
741
+ const Component = this.component;
742
+ const props = this.props;
743
+ const editor = this.editor;
744
+ const isReact19 = isReact19Plus();
745
+ const componentCanReceiveRef = canReceiveRef(Component);
746
+ const elementProps = { ...props };
747
+ if (elementProps.ref && !(isReact19 || componentCanReceiveRef)) {
748
+ delete elementProps.ref;
1045
749
  }
750
+ if (!elementProps.ref && (isReact19 || componentCanReceiveRef)) {
751
+ elementProps.ref = (ref) => {
752
+ this.ref = ref;
753
+ };
754
+ }
755
+ this.reactElement = /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Component, { ...elementProps });
756
+ (_a = editor == null ? void 0 : editor.contentComponent) == null ? void 0 : _a.setRenderer(this.id, this);
757
+ }
758
+ /**
759
+ * Re-renders the React component with new props.
760
+ */
761
+ updateProps(props = {}) {
762
+ this.props = {
763
+ ...this.props,
764
+ ...props
765
+ };
766
+ this.render();
767
+ }
768
+ /**
769
+ * Destroy the React component.
770
+ */
771
+ destroy() {
772
+ var _a;
773
+ const editor = this.editor;
774
+ (_a = editor == null ? void 0 : editor.contentComponent) == null ? void 0 : _a.removeRenderer(this.id);
775
+ }
776
+ /**
777
+ * Update the attributes of the element that holds the React component.
778
+ */
779
+ updateAttributes(attributes) {
780
+ Object.keys(attributes).forEach((key) => {
781
+ this.element.setAttribute(key, attributes[key]);
782
+ });
783
+ }
784
+ };
785
+
786
+ // src/ReactMarkViewRenderer.tsx
787
+ var import_jsx_runtime6 = (
788
+ // @ts-ignore
789
+ require("react/jsx-runtime")
790
+ );
791
+ var ReactMarkViewContext = import_react9.default.createContext({
792
+ markViewContentRef: () => {
793
+ }
794
+ });
795
+ var MarkViewContent = (props) => {
796
+ const { as: Tag = "span", ...rest } = props;
797
+ const { markViewContentRef } = import_react9.default.useContext(ReactMarkViewContext);
798
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Tag, { ...rest, ref: markViewContentRef, "data-mark-view-content": "" });
799
+ };
800
+ var ReactMarkView = class extends import_core2.MarkView {
801
+ constructor(component, props, options) {
802
+ super(component, props, options);
803
+ this.didMountContentDomElement = false;
804
+ const { as = "span", attrs, className = "" } = options || {};
805
+ const componentProps = { ...props, updateAttributes: this.updateAttributes.bind(this) };
806
+ this.contentDOMElement = document.createElement("span");
807
+ const markViewContentRef = (el) => {
808
+ if (el && this.contentDOMElement && el.firstChild !== this.contentDOMElement) {
809
+ el.appendChild(this.contentDOMElement);
810
+ this.didMountContentDomElement = true;
811
+ }
812
+ };
813
+ const context = {
814
+ markViewContentRef
815
+ };
816
+ const ReactMarkViewProvider = import_react9.default.memo((componentProps2) => {
817
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(ReactMarkViewContext.Provider, { value: context, children: import_react9.default.createElement(component, componentProps2) });
818
+ });
819
+ ReactMarkViewProvider.displayName = "ReactNodeView";
820
+ this.renderer = new ReactRenderer(ReactMarkViewProvider, {
821
+ editor: props.editor,
822
+ props: componentProps,
823
+ as,
824
+ className: `mark-${props.mark.type.name} ${className}`.trim()
825
+ });
826
+ if (attrs) {
827
+ this.renderer.updateAttributes(attrs);
828
+ }
829
+ }
830
+ get dom() {
831
+ return this.renderer.element;
832
+ }
833
+ get contentDOM() {
834
+ if (!this.didMountContentDomElement) {
835
+ return null;
836
+ }
837
+ return this.contentDOMElement;
838
+ }
839
+ };
840
+ function ReactMarkViewRenderer(component, options = {}) {
841
+ return (props) => new ReactMarkView(component, props, options);
1046
842
  }
1047
843
 
1048
- class ReactNodeView extends core.NodeView {
1049
- mount() {
1050
- const props = {
1051
- editor: this.editor,
1052
- node: this.node,
1053
- decorations: this.decorations,
1054
- selected: false,
1055
- extension: this.extension,
1056
- getPos: () => this.getPos(),
1057
- updateAttributes: (attributes = {}) => this.updateAttributes(attributes),
1058
- deleteNode: () => this.deleteNode(),
1059
- };
1060
- if (!this.component.displayName) {
1061
- const capitalizeFirstChar = (string) => {
1062
- return string.charAt(0).toUpperCase() + string.substring(1);
1063
- };
1064
- this.component.displayName = capitalizeFirstChar(this.extension.name);
1065
- }
1066
- const ReactNodeViewProvider = componentProps => {
1067
- const Component = this.component;
1068
- const onDragStart = this.onDragStart.bind(this);
1069
- const nodeViewContentRef = element => {
1070
- if (element && this.contentDOMElement && element.firstChild !== this.contentDOMElement) {
1071
- element.appendChild(this.contentDOMElement);
1072
- }
1073
- };
1074
- return (React.createElement(React.Fragment, null,
1075
- React.createElement(ReactNodeViewContext.Provider, { value: { onDragStart, nodeViewContentRef } },
1076
- React.createElement(Component, { ...componentProps }))));
1077
- };
1078
- ReactNodeViewProvider.displayName = 'ReactNodeView';
1079
- if (this.node.isLeaf) {
1080
- this.contentDOMElement = null;
1081
- }
1082
- else if (this.options.contentDOMElementTag) {
1083
- this.contentDOMElement = document.createElement(this.options.contentDOMElementTag);
1084
- }
1085
- else {
1086
- this.contentDOMElement = document.createElement(this.node.isInline ? 'span' : 'div');
1087
- }
1088
- if (this.contentDOMElement) {
1089
- // For some reason the whiteSpace prop is not inherited properly in Chrome and Safari
1090
- // With this fix it seems to work fine
1091
- // See: https://github.com/ueberdosis/tiptap/issues/1197
1092
- this.contentDOMElement.style.whiteSpace = 'inherit';
1093
- }
1094
- let as = this.node.isInline ? 'span' : 'div';
1095
- if (this.options.as) {
1096
- as = this.options.as;
1097
- }
1098
- const { className = '' } = this.options;
1099
- this.handleSelectionUpdate = this.handleSelectionUpdate.bind(this);
1100
- this.editor.on('selectionUpdate', this.handleSelectionUpdate);
1101
- this.renderer = new ReactRenderer(ReactNodeViewProvider, {
1102
- editor: this.editor,
1103
- props,
1104
- as,
1105
- className: `node-${this.node.type.name} ${className}`.trim(),
1106
- attrs: this.options.attrs,
1107
- });
844
+ // src/ReactNodeViewRenderer.tsx
845
+ var import_core3 = require("@tiptap/core");
846
+ var import_react10 = require("react");
847
+ var import_jsx_runtime7 = require("react/jsx-runtime");
848
+ var ReactNodeView = class extends import_core3.NodeView {
849
+ constructor(component, props, options) {
850
+ super(component, props, options);
851
+ if (!this.node.isLeaf) {
852
+ if (this.options.contentDOMElementTag) {
853
+ this.contentDOMElement = document.createElement(this.options.contentDOMElementTag);
854
+ } else {
855
+ this.contentDOMElement = document.createElement(this.node.isInline ? "span" : "div");
856
+ }
857
+ this.contentDOMElement.dataset.nodeViewContentReact = "";
858
+ this.contentDOMElement.dataset.nodeViewWrapper = "";
859
+ this.contentDOMElement.style.whiteSpace = "inherit";
860
+ const contentTarget = this.dom.querySelector("[data-node-view-content]");
861
+ if (!contentTarget) {
862
+ return;
863
+ }
864
+ contentTarget.appendChild(this.contentDOMElement);
1108
865
  }
1109
- get dom() {
1110
- var _a;
1111
- if (this.renderer.element.firstElementChild
1112
- && !((_a = this.renderer.element.firstElementChild) === null || _a === void 0 ? void 0 : _a.hasAttribute('data-node-view-wrapper'))) {
1113
- throw Error('Please use the NodeViewWrapper component for your node view.');
1114
- }
1115
- return this.renderer.element;
866
+ }
867
+ /**
868
+ * Setup the React component.
869
+ * Called on initialization.
870
+ */
871
+ mount() {
872
+ const props = {
873
+ editor: this.editor,
874
+ node: this.node,
875
+ decorations: this.decorations,
876
+ innerDecorations: this.innerDecorations,
877
+ view: this.view,
878
+ selected: false,
879
+ extension: this.extension,
880
+ HTMLAttributes: this.HTMLAttributes,
881
+ getPos: () => this.getPos(),
882
+ updateAttributes: (attributes = {}) => this.updateAttributes(attributes),
883
+ deleteNode: () => this.deleteNode(),
884
+ ref: (0, import_react10.createRef)()
885
+ };
886
+ if (!this.component.displayName) {
887
+ const capitalizeFirstChar = (string) => {
888
+ return string.charAt(0).toUpperCase() + string.substring(1);
889
+ };
890
+ this.component.displayName = capitalizeFirstChar(this.extension.name);
1116
891
  }
1117
- get contentDOM() {
1118
- if (this.node.isLeaf) {
1119
- return null;
892
+ const onDragStart = this.onDragStart.bind(this);
893
+ const nodeViewContentRef = (element) => {
894
+ if (element && this.contentDOMElement && element.firstChild !== this.contentDOMElement) {
895
+ if (element.hasAttribute("data-node-view-wrapper")) {
896
+ element.removeAttribute("data-node-view-wrapper");
1120
897
  }
1121
- return this.contentDOMElement;
898
+ element.appendChild(this.contentDOMElement);
899
+ }
900
+ };
901
+ const context = { onDragStart, nodeViewContentRef };
902
+ const Component = this.component;
903
+ const ReactNodeViewProvider = (0, import_react10.memo)((componentProps) => {
904
+ return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(ReactNodeViewContext.Provider, { value: context, children: (0, import_react10.createElement)(Component, componentProps) });
905
+ });
906
+ ReactNodeViewProvider.displayName = "ReactNodeView";
907
+ let as = this.node.isInline ? "span" : "div";
908
+ if (this.options.as) {
909
+ as = this.options.as;
1122
910
  }
1123
- handleSelectionUpdate() {
1124
- const { from, to } = this.editor.state.selection;
1125
- if (from <= this.getPos() && to >= this.getPos() + this.node.nodeSize) {
1126
- if (this.renderer.props.selected) {
1127
- return;
1128
- }
1129
- this.selectNode();
1130
- }
1131
- else {
1132
- if (!this.renderer.props.selected) {
1133
- return;
1134
- }
1135
- this.deselectNode();
1136
- }
911
+ const { className = "" } = this.options;
912
+ this.handleSelectionUpdate = this.handleSelectionUpdate.bind(this);
913
+ this.renderer = new ReactRenderer(ReactNodeViewProvider, {
914
+ editor: this.editor,
915
+ props,
916
+ as,
917
+ className: `node-${this.node.type.name} ${className}`.trim()
918
+ });
919
+ this.editor.on("selectionUpdate", this.handleSelectionUpdate);
920
+ this.updateElementAttributes();
921
+ }
922
+ /**
923
+ * Return the DOM element.
924
+ * This is the element that will be used to display the node view.
925
+ */
926
+ get dom() {
927
+ var _a;
928
+ if (this.renderer.element.firstElementChild && !((_a = this.renderer.element.firstElementChild) == null ? void 0 : _a.hasAttribute("data-node-view-wrapper"))) {
929
+ throw Error("Please use the NodeViewWrapper component for your node view.");
1137
930
  }
1138
- update(node, decorations) {
1139
- const updateProps = (props) => {
1140
- this.renderer.updateProps(props);
1141
- };
1142
- if (node.type !== this.node.type) {
1143
- return false;
1144
- }
1145
- if (typeof this.options.update === 'function') {
1146
- const oldNode = this.node;
1147
- const oldDecorations = this.decorations;
1148
- this.node = node;
1149
- this.decorations = decorations;
1150
- return this.options.update({
1151
- oldNode,
1152
- oldDecorations,
1153
- newNode: node,
1154
- newDecorations: decorations,
1155
- updateProps: () => updateProps({ node, decorations }),
1156
- });
1157
- }
1158
- if (node === this.node && this.decorations === decorations) {
1159
- return true;
1160
- }
1161
- this.node = node;
1162
- this.decorations = decorations;
1163
- updateProps({ node, decorations });
1164
- return true;
931
+ return this.renderer.element;
932
+ }
933
+ /**
934
+ * Return the content DOM element.
935
+ * This is the element that will be used to display the rich-text content of the node.
936
+ */
937
+ get contentDOM() {
938
+ if (this.node.isLeaf) {
939
+ return null;
1165
940
  }
1166
- selectNode() {
1167
- this.renderer.updateProps({
1168
- selected: true,
1169
- });
1170
- this.renderer.element.classList.add('ProseMirror-selectednode');
941
+ return this.contentDOMElement;
942
+ }
943
+ /**
944
+ * On editor selection update, check if the node is selected.
945
+ * If it is, call `selectNode`, otherwise call `deselectNode`.
946
+ */
947
+ handleSelectionUpdate() {
948
+ const { from, to } = this.editor.state.selection;
949
+ const pos = this.getPos();
950
+ if (typeof pos !== "number") {
951
+ return;
1171
952
  }
1172
- deselectNode() {
1173
- this.renderer.updateProps({
1174
- selected: false,
1175
- });
1176
- this.renderer.element.classList.remove('ProseMirror-selectednode');
953
+ if (from <= pos && to >= pos + this.node.nodeSize) {
954
+ if (this.renderer.props.selected) {
955
+ return;
956
+ }
957
+ this.selectNode();
958
+ } else {
959
+ if (!this.renderer.props.selected) {
960
+ return;
961
+ }
962
+ this.deselectNode();
1177
963
  }
1178
- destroy() {
1179
- this.renderer.destroy();
1180
- this.editor.off('selectionUpdate', this.handleSelectionUpdate);
1181
- this.contentDOMElement = null;
964
+ }
965
+ /**
966
+ * On update, update the React component.
967
+ * To prevent unnecessary updates, the `update` option can be used.
968
+ */
969
+ update(node, decorations, innerDecorations) {
970
+ const rerenderComponent = (props) => {
971
+ this.renderer.updateProps(props);
972
+ if (typeof this.options.attrs === "function") {
973
+ this.updateElementAttributes();
974
+ }
975
+ };
976
+ if (node.type !== this.node.type) {
977
+ return false;
1182
978
  }
1183
- }
979
+ if (typeof this.options.update === "function") {
980
+ const oldNode = this.node;
981
+ const oldDecorations = this.decorations;
982
+ const oldInnerDecorations = this.innerDecorations;
983
+ this.node = node;
984
+ this.decorations = decorations;
985
+ this.innerDecorations = innerDecorations;
986
+ return this.options.update({
987
+ oldNode,
988
+ oldDecorations,
989
+ newNode: node,
990
+ newDecorations: decorations,
991
+ oldInnerDecorations,
992
+ innerDecorations,
993
+ updateProps: () => rerenderComponent({ node, decorations, innerDecorations })
994
+ });
995
+ }
996
+ if (node === this.node && this.decorations === decorations && this.innerDecorations === innerDecorations) {
997
+ return true;
998
+ }
999
+ this.node = node;
1000
+ this.decorations = decorations;
1001
+ this.innerDecorations = innerDecorations;
1002
+ rerenderComponent({ node, decorations, innerDecorations });
1003
+ return true;
1004
+ }
1005
+ /**
1006
+ * Select the node.
1007
+ * Add the `selected` prop and the `ProseMirror-selectednode` class.
1008
+ */
1009
+ selectNode() {
1010
+ this.renderer.updateProps({
1011
+ selected: true
1012
+ });
1013
+ this.renderer.element.classList.add("ProseMirror-selectednode");
1014
+ }
1015
+ /**
1016
+ * Deselect the node.
1017
+ * Remove the `selected` prop and the `ProseMirror-selectednode` class.
1018
+ */
1019
+ deselectNode() {
1020
+ this.renderer.updateProps({
1021
+ selected: false
1022
+ });
1023
+ this.renderer.element.classList.remove("ProseMirror-selectednode");
1024
+ }
1025
+ /**
1026
+ * Destroy the React component instance.
1027
+ */
1028
+ destroy() {
1029
+ this.renderer.destroy();
1030
+ this.editor.off("selectionUpdate", this.handleSelectionUpdate);
1031
+ this.contentDOMElement = null;
1032
+ }
1033
+ /**
1034
+ * Update the attributes of the top-level element that holds the React component.
1035
+ * Applying the attributes defined in the `attrs` option.
1036
+ */
1037
+ updateElementAttributes() {
1038
+ if (this.options.attrs) {
1039
+ let attrsObj = {};
1040
+ if (typeof this.options.attrs === "function") {
1041
+ const extensionAttributes = this.editor.extensionManager.attributes;
1042
+ const HTMLAttributes = (0, import_core3.getRenderedAttributes)(this.node, extensionAttributes);
1043
+ attrsObj = this.options.attrs({ node: this.node, HTMLAttributes });
1044
+ } else {
1045
+ attrsObj = this.options.attrs;
1046
+ }
1047
+ this.renderer.updateAttributes(attrsObj);
1048
+ }
1049
+ }
1050
+ };
1184
1051
  function ReactNodeViewRenderer(component, options) {
1185
- return (props) => {
1186
- // try to get the parent component
1187
- // this is important for vue devtools to show the component hierarchy correctly
1188
- // maybe it’s `undefined` because <editor-content> isn’t rendered yet
1189
- if (!props.editor.contentComponent) {
1190
- return {};
1191
- }
1192
- return new ReactNodeView(component, props, options);
1193
- };
1052
+ return (props) => {
1053
+ if (!props.editor.contentComponent) {
1054
+ return {};
1055
+ }
1056
+ return new ReactNodeView(component, props, options);
1057
+ };
1194
1058
  }
1195
1059
 
1196
- exports.BubbleMenu = BubbleMenu;
1197
- exports.Editor = Editor;
1198
- exports.EditorConsumer = EditorConsumer;
1199
- exports.EditorContent = EditorContent;
1200
- exports.EditorContext = EditorContext;
1201
- exports.EditorProvider = EditorProvider;
1202
- exports.FloatingMenu = FloatingMenu;
1203
- exports.NodeViewContent = NodeViewContent;
1204
- exports.NodeViewWrapper = NodeViewWrapper;
1205
- exports.PureEditorContent = PureEditorContent;
1206
- exports.ReactNodeViewContext = ReactNodeViewContext;
1207
- exports.ReactNodeViewRenderer = ReactNodeViewRenderer;
1208
- exports.ReactRenderer = ReactRenderer;
1209
- exports.useCurrentEditor = useCurrentEditor;
1210
- exports.useEditor = useEditor;
1211
- exports.useEditorState = useEditorState;
1212
- exports.useReactNodeView = useReactNodeView;
1213
- Object.keys(core).forEach(function (k) {
1214
- if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
1215
- enumerable: true,
1216
- get: function () { return core[k]; }
1217
- });
1060
+ // src/index.ts
1061
+ __reExport(index_exports, require("@tiptap/core"), module.exports);
1062
+ // Annotate the CommonJS export names for ESM import in node:
1063
+ 0 && (module.exports = {
1064
+ EditorConsumer,
1065
+ EditorContent,
1066
+ EditorContext,
1067
+ EditorProvider,
1068
+ MarkViewContent,
1069
+ NodeViewContent,
1070
+ NodeViewWrapper,
1071
+ PureEditorContent,
1072
+ ReactMarkView,
1073
+ ReactMarkViewContext,
1074
+ ReactMarkViewRenderer,
1075
+ ReactNodeView,
1076
+ ReactNodeViewContentProvider,
1077
+ ReactNodeViewContext,
1078
+ ReactNodeViewRenderer,
1079
+ ReactRenderer,
1080
+ useCurrentEditor,
1081
+ useEditor,
1082
+ useEditorState,
1083
+ useReactNodeView,
1084
+ ...require("@tiptap/core")
1218
1085
  });
1219
- //# sourceMappingURL=index.cjs.map
1086
+ //# sourceMappingURL=index.cjs.map