@tiptap/react 2.11.7 → 3.0.0-beta.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 (59) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +5 -1
  3. package/dist/index.cjs +967 -1473
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.cts +345 -0
  6. package/dist/index.d.ts +344 -12
  7. package/dist/index.js +916 -1452
  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 +30 -18
  16. package/src/Context.tsx +18 -15
  17. package/src/Editor.ts +8 -8
  18. package/src/EditorContent.tsx +14 -22
  19. package/src/NodeViewContent.tsx +12 -8
  20. package/src/NodeViewWrapper.tsx +2 -2
  21. package/src/ReactMarkViewRenderer.tsx +109 -0
  22. package/src/ReactNodeViewRenderer.tsx +32 -50
  23. package/src/ReactRenderer.tsx +17 -26
  24. package/src/index.ts +1 -2
  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/useEditor.ts +32 -26
  29. package/src/useEditorState.ts +14 -19
  30. package/src/useReactNodeView.ts +21 -5
  31. package/dist/BubbleMenu.d.ts +0 -12
  32. package/dist/BubbleMenu.d.ts.map +0 -1
  33. package/dist/Context.d.ts +0 -25
  34. package/dist/Context.d.ts.map +0 -1
  35. package/dist/Editor.d.ts +0 -14
  36. package/dist/Editor.d.ts.map +0 -1
  37. package/dist/EditorContent.d.ts +0 -21
  38. package/dist/EditorContent.d.ts.map +0 -1
  39. package/dist/FloatingMenu.d.ts +0 -11
  40. package/dist/FloatingMenu.d.ts.map +0 -1
  41. package/dist/NodeViewContent.d.ts +0 -7
  42. package/dist/NodeViewContent.d.ts.map +0 -1
  43. package/dist/NodeViewWrapper.d.ts +0 -7
  44. package/dist/NodeViewWrapper.d.ts.map +0 -1
  45. package/dist/ReactNodeViewRenderer.d.ts +0 -96
  46. package/dist/ReactNodeViewRenderer.d.ts.map +0 -1
  47. package/dist/ReactRenderer.d.ts +0 -71
  48. package/dist/ReactRenderer.d.ts.map +0 -1
  49. package/dist/index.d.ts.map +0 -1
  50. package/dist/index.umd.js +0 -1540
  51. package/dist/index.umd.js.map +0 -1
  52. package/dist/useEditor.d.ts +0 -39
  53. package/dist/useEditor.d.ts.map +0 -1
  54. package/dist/useEditorState.d.ts +0 -45
  55. package/dist/useEditorState.d.ts.map +0 -1
  56. package/dist/useReactNodeView.d.ts +0 -7
  57. package/dist/useReactNodeView.d.ts.map +0 -1
  58. package/src/BubbleMenu.tsx +0 -57
  59. package/src/FloatingMenu.tsx +0 -64
package/dist/index.cjs CHANGED
@@ -1,1545 +1,1039 @@
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
- function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
10
-
11
- var React__default = /*#__PURE__*/_interopDefaultCompat(React);
12
- var ReactDOM__default = /*#__PURE__*/_interopDefaultCompat(ReactDOM);
13
-
14
- function getDefaultExportFromCjs (x) {
15
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
16
- }
17
-
18
- var shim = {exports: {}};
19
-
20
- var useSyncExternalStoreShim_production_min = {};
21
-
22
- /**
23
- * @license React
24
- * use-sync-external-store-shim.production.min.js
25
- *
26
- * Copyright (c) Facebook, Inc. and its affiliates.
27
- *
28
- * This source code is licensed under the MIT license found in the
29
- * LICENSE file in the root directory of this source tree.
30
- */
31
-
32
- var hasRequiredUseSyncExternalStoreShim_production_min;
33
-
34
- function requireUseSyncExternalStoreShim_production_min () {
35
- if (hasRequiredUseSyncExternalStoreShim_production_min) return useSyncExternalStoreShim_production_min;
36
- hasRequiredUseSyncExternalStoreShim_production_min = 1;
37
- var e=React__default.default;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}
38
- 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;
39
- return useSyncExternalStoreShim_production_min;
40
- }
41
-
42
- var useSyncExternalStoreShim_development = {};
43
-
44
- /**
45
- * @license React
46
- * use-sync-external-store-shim.development.js
47
- *
48
- * Copyright (c) Facebook, Inc. and its affiliates.
49
- *
50
- * This source code is licensed under the MIT license found in the
51
- * LICENSE file in the root directory of this source tree.
52
- */
53
-
54
- var hasRequiredUseSyncExternalStoreShim_development;
55
-
56
- function requireUseSyncExternalStoreShim_development () {
57
- if (hasRequiredUseSyncExternalStoreShim_development) return useSyncExternalStoreShim_development;
58
- hasRequiredUseSyncExternalStoreShim_development = 1;
59
-
60
- if (process.env.NODE_ENV !== "production") {
61
- (function() {
62
-
63
- /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
64
- if (
65
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
66
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===
67
- 'function'
68
- ) {
69
- __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
70
- }
71
- var React = React__default.default;
72
-
73
- var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
74
-
75
- function error(format) {
76
- {
77
- {
78
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
79
- args[_key2 - 1] = arguments[_key2];
80
- }
81
-
82
- printWarning('error', format, args);
83
- }
84
- }
85
- }
86
-
87
- function printWarning(level, format, args) {
88
- // When changing this logic, you might want to also
89
- // update consoleWithStackDev.www.js as well.
90
- {
91
- var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
92
- var stack = ReactDebugCurrentFrame.getStackAddendum();
93
-
94
- if (stack !== '') {
95
- format += '%s';
96
- args = args.concat([stack]);
97
- } // eslint-disable-next-line react-internal/safe-string-coercion
98
-
99
-
100
- var argsWithFormat = args.map(function (item) {
101
- return String(item);
102
- }); // Careful: RN currently depends on this prefix
103
-
104
- argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
105
- // breaks IE9: https://github.com/facebook/react/issues/13610
106
- // eslint-disable-next-line react-internal/no-production-logging
107
-
108
- Function.prototype.apply.call(console[level], console, argsWithFormat);
109
- }
110
- }
111
-
112
- /**
113
- * inlined Object.is polyfill to avoid requiring consumers ship their own
114
- * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
115
- */
116
- function is(x, y) {
117
- return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
118
- ;
119
- }
120
-
121
- var objectIs = typeof Object.is === 'function' ? Object.is : is;
122
-
123
- // dispatch for CommonJS interop named imports.
124
-
125
- var useState = React.useState,
126
- useEffect = React.useEffect,
127
- useLayoutEffect = React.useLayoutEffect,
128
- useDebugValue = React.useDebugValue;
129
- var didWarnOld18Alpha = false;
130
- var didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works
131
- // because of a very particular set of implementation details and assumptions
132
- // -- change any one of them and it will break. The most important assumption
133
- // is that updates are always synchronous, because concurrent rendering is
134
- // only available in versions of React that also have a built-in
135
- // useSyncExternalStore API. And we only use this shim when the built-in API
136
- // does not exist.
137
- //
138
- // Do not assume that the clever hacks used by this hook also work in general.
139
- // The point of this shim is to replace the need for hacks by other libraries.
140
-
141
- function useSyncExternalStore(subscribe, getSnapshot, // Note: The shim does not use getServerSnapshot, because pre-18 versions of
142
- // React do not expose a way to check if we're hydrating. So users of the shim
143
- // will need to track that themselves and return the correct value
144
- // from `getSnapshot`.
145
- getServerSnapshot) {
146
- {
147
- if (!didWarnOld18Alpha) {
148
- if (React.startTransition !== undefined) {
149
- didWarnOld18Alpha = true;
150
-
151
- 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.');
152
- }
153
- }
154
- } // Read the current snapshot from the store on every render. Again, this
155
- // breaks the rules of React, and only works here because of specific
156
- // implementation details, most importantly that updates are
157
- // always synchronous.
158
-
159
-
160
- var value = getSnapshot();
161
-
162
- {
163
- if (!didWarnUncachedGetSnapshot) {
164
- var cachedValue = getSnapshot();
165
-
166
- if (!objectIs(value, cachedValue)) {
167
- error('The result of getSnapshot should be cached to avoid an infinite loop');
168
-
169
- didWarnUncachedGetSnapshot = true;
170
- }
171
- }
172
- } // Because updates are synchronous, we don't queue them. Instead we force a
173
- // re-render whenever the subscribed state changes by updating an some
174
- // arbitrary useState hook. Then, during render, we call getSnapshot to read
175
- // the current value.
176
- //
177
- // Because we don't actually use the state returned by the useState hook, we
178
- // can save a bit of memory by storing other stuff in that slot.
179
- //
180
- // To implement the early bailout, we need to track some things on a mutable
181
- // object. Usually, we would put that in a useRef hook, but we can stash it in
182
- // our useState hook instead.
183
- //
184
- // To force a re-render, we call forceUpdate({inst}). That works because the
185
- // new object always fails an equality check.
186
-
187
-
188
- var _useState = useState({
189
- inst: {
190
- value: value,
191
- getSnapshot: getSnapshot
192
- }
193
- }),
194
- inst = _useState[0].inst,
195
- forceUpdate = _useState[1]; // Track the latest getSnapshot function with a ref. This needs to be updated
196
- // in the layout phase so we can access it during the tearing check that
197
- // happens on subscribe.
198
-
199
-
200
- useLayoutEffect(function () {
201
- inst.value = value;
202
- inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the
203
- // commit phase if there was an interleaved mutation. In concurrent mode
204
- // this can happen all the time, but even in synchronous mode, an earlier
205
- // effect may have mutated the store.
206
-
207
- if (checkIfSnapshotChanged(inst)) {
208
- // Force a re-render.
209
- forceUpdate({
210
- inst: inst
211
- });
212
- }
213
- }, [subscribe, value, getSnapshot]);
214
- useEffect(function () {
215
- // Check for changes right before subscribing. Subsequent changes will be
216
- // detected in the subscription handler.
217
- if (checkIfSnapshotChanged(inst)) {
218
- // Force a re-render.
219
- forceUpdate({
220
- inst: inst
221
- });
222
- }
223
-
224
- var handleStoreChange = function () {
225
- // TODO: Because there is no cross-renderer API for batching updates, it's
226
- // up to the consumer of this library to wrap their subscription event
227
- // with unstable_batchedUpdates. Should we try to detect when this isn't
228
- // the case and print a warning in development?
229
- // The store changed. Check if the snapshot changed since the last time we
230
- // read from the store.
231
- if (checkIfSnapshotChanged(inst)) {
232
- // Force a re-render.
233
- forceUpdate({
234
- inst: inst
235
- });
236
- }
237
- }; // Subscribe to the store and return a clean-up function.
238
-
239
-
240
- return subscribe(handleStoreChange);
241
- }, [subscribe]);
242
- useDebugValue(value);
243
- return value;
244
- }
245
-
246
- function checkIfSnapshotChanged(inst) {
247
- var latestGetSnapshot = inst.getSnapshot;
248
- var prevValue = inst.value;
249
-
250
- try {
251
- var nextValue = latestGetSnapshot();
252
- return !objectIs(prevValue, nextValue);
253
- } catch (error) {
254
- return true;
255
- }
256
- }
257
-
258
- function useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {
259
- // Note: The shim does not use getServerSnapshot, because pre-18 versions of
260
- // React do not expose a way to check if we're hydrating. So users of the shim
261
- // will need to track that themselves and return the correct value
262
- // from `getSnapshot`.
263
- return getSnapshot();
264
- }
265
-
266
- var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');
267
-
268
- var isServerEnvironment = !canUseDOM;
269
-
270
- var shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore;
271
- var useSyncExternalStore$2 = React.useSyncExternalStore !== undefined ? React.useSyncExternalStore : shim;
272
-
273
- useSyncExternalStoreShim_development.useSyncExternalStore = useSyncExternalStore$2;
274
- /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
275
- if (
276
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
277
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===
278
- 'function'
279
- ) {
280
- __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
281
- }
282
-
283
- })();
284
- }
285
- return useSyncExternalStoreShim_development;
286
- }
287
-
288
- if (process.env.NODE_ENV === 'production') {
289
- shim.exports = requireUseSyncExternalStoreShim_production_min();
290
- } else {
291
- shim.exports = requireUseSyncExternalStoreShim_development();
292
- }
293
-
294
- var shimExports = shim.exports;
295
-
296
- const mergeRefs = (...refs) => {
297
- return (node) => {
298
- refs.forEach(ref => {
299
- if (typeof ref === 'function') {
300
- ref(node);
301
- }
302
- else if (ref) {
303
- ref.current = node;
304
- }
305
- });
306
- };
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 });
11
+ };
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;
19
+ };
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");
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
+ };
307
76
  };
308
- /**
309
- * This component renders all of the editor's node views.
310
- */
311
- const Portals = ({ contentComponent, }) => {
312
- // For performance reasons, we render the node view portals on state changes only
313
- const renderers = shimExports.useSyncExternalStore(contentComponent.subscribe, contentComponent.getSnapshot, contentComponent.getServerSnapshot);
314
- // This allows us to directly render the portals without any additional wrapper
315
- return (React__default.default.createElement(React__default.default.Fragment, null, Object.values(renderers)));
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) });
316
84
  };
317
85
  function getInstance() {
318
- const subscribers = new Set();
319
- let renderers = {};
320
- return {
321
- /**
322
- * Subscribe to the editor instance's changes.
323
- */
324
- subscribe(callback) {
325
- subscribers.add(callback);
326
- return () => {
327
- subscribers.delete(callback);
328
- };
329
- },
330
- getSnapshot() {
331
- return renderers;
332
- },
333
- getServerSnapshot() {
334
- return renderers;
335
- },
336
- /**
337
- * Adds a new NodeView Renderer to the editor.
338
- */
339
- setRenderer(id, renderer) {
340
- renderers = {
341
- ...renderers,
342
- [id]: ReactDOM__default.default.createPortal(renderer.reactElement, renderer.element, id),
343
- };
344
- subscribers.forEach(subscriber => subscriber());
345
- },
346
- /**
347
- * Removes a NodeView Renderer from the editor.
348
- */
349
- removeRenderer(id) {
350
- const nextRenderers = { ...renderers };
351
- delete nextRenderers[id];
352
- renderers = nextRenderers;
353
- subscribers.forEach(subscriber => subscriber());
354
- },
355
- };
356
- }
357
- class PureEditorContent extends React__default.default.Component {
358
- constructor(props) {
359
- var _a;
360
- super(props);
361
- this.editorContentRef = React__default.default.createRef();
362
- this.initialized = false;
363
- this.state = {
364
- hasContentComponentInitialized: Boolean((_a = props.editor) === null || _a === void 0 ? void 0 : _a.contentComponent),
365
- };
366
- }
367
- componentDidMount() {
368
- this.init();
369
- }
370
- componentDidUpdate() {
371
- this.init();
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());
372
122
  }
373
- init() {
374
- const editor = this.props.editor;
375
- if (editor && !editor.isDestroyed && editor.options.element) {
376
- if (editor.contentComponent) {
377
- return;
378
- }
379
- const element = this.editorContentRef.current;
380
- element.append(...editor.options.element.childNodes);
381
- editor.setOptions({
382
- element,
383
- });
384
- editor.contentComponent = getInstance();
385
- // Has the content component been initialized?
386
- if (!this.state.hasContentComponentInitialized) {
387
- // Subscribe to the content component
388
- this.unsubscribeToContentComponent = editor.contentComponent.subscribe(() => {
389
- this.setState(prevState => {
390
- if (!prevState.hasContentComponentInitialized) {
391
- return {
392
- hasContentComponentInitialized: true,
393
- };
394
- }
395
- return prevState;
396
- });
397
- // Unsubscribe to previous content component
398
- if (this.unsubscribeToContentComponent) {
399
- this.unsubscribeToContentComponent();
400
- }
401
- });
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
+ };
402
160
  }
403
- editor.createNodeViews();
404
- this.initialized = true;
405
- }
406
- }
407
- componentWillUnmount() {
408
- const editor = this.props.editor;
409
- if (!editor) {
410
- return;
411
- }
412
- this.initialized = false;
413
- if (!editor.isDestroyed) {
414
- editor.view.setProps({
415
- nodeViews: {},
416
- });
417
- }
418
- if (this.unsubscribeToContentComponent) {
161
+ return prevState;
162
+ });
163
+ if (this.unsubscribeToContentComponent) {
419
164
  this.unsubscribeToContentComponent();
420
- }
421
- editor.contentComponent = null;
422
- if (!editor.options.element.firstChild) {
423
- return;
424
- }
425
- const newElement = document.createElement('div');
426
- newElement.append(...editor.options.element.childNodes);
427
- editor.setOptions({
428
- element: newElement,
165
+ }
429
166
  });
167
+ }
168
+ editor.createNodeViews();
169
+ this.initialized = true;
430
170
  }
431
- render() {
432
- const { editor, innerRef, ...rest } = this.props;
433
- return (React__default.default.createElement(React__default.default.Fragment, null,
434
- React__default.default.createElement("div", { ref: mergeRefs(innerRef, this.editorContentRef), ...rest }),
435
- (editor === null || editor === void 0 ? void 0 : editor.contentComponent) && React__default.default.createElement(Portals, { contentComponent: editor.contentComponent })));
171
+ }
172
+ componentWillUnmount() {
173
+ var _a;
174
+ const editor = this.props.editor;
175
+ if (!editor) {
176
+ return;
436
177
  }
437
- }
438
- // EditorContent should be re-created whenever the Editor instance changes
439
- const EditorContentWithKey = React.forwardRef((props, ref) => {
440
- const key = React__default.default.useMemo(() => {
441
- return Math.floor(Math.random() * 0xffffffff).toString();
442
- // eslint-disable-next-line react-hooks/exhaustive-deps
443
- }, [props.editor]);
444
- // Can't use JSX here because it conflicts with the type definition of Vue's JSX, so use createElement
445
- return React__default.default.createElement(PureEditorContent, {
446
- key,
447
- innerRef: ref,
448
- ...props,
449
- });
450
- });
451
- const EditorContent = React__default.default.memo(EditorContentWithKey);
452
-
453
- var react = function equal(a, b) {
454
- if (a === b) return true;
455
-
456
- if (a && b && typeof a == 'object' && typeof b == 'object') {
457
- if (a.constructor !== b.constructor) return false;
458
-
459
- var length, i, keys;
460
- if (Array.isArray(a)) {
461
- length = a.length;
462
- if (length != b.length) return false;
463
- for (i = length; i-- !== 0;)
464
- if (!equal(a[i], b[i])) return false;
465
- return true;
178
+ this.initialized = false;
179
+ if (!editor.isDestroyed) {
180
+ editor.view.setProps({
181
+ nodeViews: {}
182
+ });
466
183
  }
467
-
468
-
469
- if ((a instanceof Map) && (b instanceof Map)) {
470
- if (a.size !== b.size) return false;
471
- for (i of a.entries())
472
- if (!b.has(i[0])) return false;
473
- for (i of a.entries())
474
- if (!equal(i[1], b.get(i[0]))) return false;
475
- return true;
184
+ if (this.unsubscribeToContentComponent) {
185
+ this.unsubscribeToContentComponent();
476
186
  }
477
-
478
- if ((a instanceof Set) && (b instanceof Set)) {
479
- if (a.size !== b.size) return false;
480
- for (i of a.entries())
481
- if (!b.has(i[0])) return false;
482
- return true;
187
+ editor.contentComponent = null;
188
+ if (!((_a = editor.options.element) == null ? void 0 : _a.firstChild)) {
189
+ return;
483
190
  }
484
-
485
- if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
486
- length = a.length;
487
- if (length != b.length) return false;
488
- for (i = length; i-- !== 0;)
489
- if (a[i] !== b[i]) return false;
490
- return true;
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();
209
+ }, [props.editor]);
210
+ return import_react.default.createElement(PureEditorContent, {
211
+ key,
212
+ innerRef: ref,
213
+ ...props
214
+ });
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");
223
+
224
+ // src/useEditorState.ts
225
+ var import_react2 = __toESM(require("fast-deep-equal/es6/react"), 1);
226
+ var import_react3 = require("react");
227
+ var import_with_selector = require("use-sync-external-store/shim/with-selector");
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;
491
247
  }
492
-
493
-
494
- if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
495
- if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
496
- if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
497
-
498
- keys = Object.keys(a);
499
- length = keys.length;
500
- if (length !== Object.keys(b).length) return false;
501
-
502
- for (i = length; i-- !== 0;)
503
- if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
504
-
505
- for (i = length; i-- !== 0;) {
506
- var key = keys[i];
507
-
508
- if (key === '_owner' && a.$$typeof) {
509
- // React-specific: avoid traversing React elements' _owner.
510
- // _owner contains circular references
511
- // and is not needed when comparing the actual elements (and not their owners)
512
- continue;
513
- }
514
-
515
- if (!equal(a[key], b[key])) return false;
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);
265
+ };
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
+ };
516
282
  }
517
-
518
- return true;
283
+ return void 0;
519
284
  }
520
-
521
- // true if both NaN, false otherwise
522
- return a!==a && b!==b;
523
285
  };
524
-
525
- var deepEqual = /*@__PURE__*/getDefaultExportFromCjs(react);
526
-
527
- var withSelector = {exports: {}};
528
-
529
- var withSelector_production_min = {};
530
-
531
- /**
532
- * @license React
533
- * use-sync-external-store-shim/with-selector.production.min.js
534
- *
535
- * Copyright (c) Facebook, Inc. and its affiliates.
536
- *
537
- * This source code is licensed under the MIT license found in the
538
- * LICENSE file in the root directory of this source tree.
539
- */
540
-
541
- var hasRequiredWithSelector_production_min;
542
-
543
- function requireWithSelector_production_min () {
544
- if (hasRequiredWithSelector_production_min) return withSelector_production_min;
545
- hasRequiredWithSelector_production_min = 1;
546
- var h=React__default.default,n=shimExports;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;
547
- 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]);
548
- u(function(){f.hasValue=!0;f.value=d;},[d]);w(d);return d};
549
- return withSelector_production_min;
550
- }
551
-
552
- var withSelector_development = {};
553
-
554
- /**
555
- * @license React
556
- * use-sync-external-store-shim/with-selector.development.js
557
- *
558
- * Copyright (c) Facebook, Inc. and its affiliates.
559
- *
560
- * This source code is licensed under the MIT license found in the
561
- * LICENSE file in the root directory of this source tree.
562
- */
563
-
564
- var hasRequiredWithSelector_development;
565
-
566
- function requireWithSelector_development () {
567
- if (hasRequiredWithSelector_development) return withSelector_development;
568
- hasRequiredWithSelector_development = 1;
569
-
570
- if (process.env.NODE_ENV !== "production") {
571
- (function() {
572
-
573
- /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
574
- if (
575
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
576
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===
577
- 'function'
578
- ) {
579
- __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
580
- }
581
- var React = React__default.default;
582
- var shim = shimExports;
583
-
584
- /**
585
- * inlined Object.is polyfill to avoid requiring consumers ship their own
586
- * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
587
- */
588
- function is(x, y) {
589
- return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
590
- ;
591
- }
592
-
593
- var objectIs = typeof Object.is === 'function' ? Object.is : is;
594
-
595
- var useSyncExternalStore = shim.useSyncExternalStore;
596
-
597
- // for CommonJS interop.
598
-
599
- var useRef = React.useRef,
600
- useEffect = React.useEffect,
601
- useMemo = React.useMemo,
602
- useDebugValue = React.useDebugValue; // Same as useSyncExternalStore, but supports selector and isEqual arguments.
603
-
604
- function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {
605
- // Use this to track the rendered snapshot.
606
- var instRef = useRef(null);
607
- var inst;
608
-
609
- if (instRef.current === null) {
610
- inst = {
611
- hasValue: false,
612
- value: null
613
- };
614
- instRef.current = inst;
615
- } else {
616
- inst = instRef.current;
617
- }
618
-
619
- var _useMemo = useMemo(function () {
620
- // Track the memoized state using closure variables that are local to this
621
- // memoized instance of a getSnapshot function. Intentionally not using a
622
- // useRef hook, because that state would be shared across all concurrent
623
- // copies of the hook/component.
624
- var hasMemo = false;
625
- var memoizedSnapshot;
626
- var memoizedSelection;
627
-
628
- var memoizedSelector = function (nextSnapshot) {
629
- if (!hasMemo) {
630
- // The first time the hook is called, there is no memoized result.
631
- hasMemo = true;
632
- memoizedSnapshot = nextSnapshot;
633
-
634
- var _nextSelection = selector(nextSnapshot);
635
-
636
- if (isEqual !== undefined) {
637
- // Even if the selector has changed, the currently rendered selection
638
- // may be equal to the new selection. We should attempt to reuse the
639
- // current value if possible, to preserve downstream memoizations.
640
- if (inst.hasValue) {
641
- var currentSelection = inst.value;
642
-
643
- if (isEqual(currentSelection, _nextSelection)) {
644
- memoizedSelection = currentSelection;
645
- return currentSelection;
646
- }
647
- }
648
- }
649
-
650
- memoizedSelection = _nextSelection;
651
- return _nextSelection;
652
- } // We may be able to reuse the previous invocation's result.
653
-
654
-
655
- // We may be able to reuse the previous invocation's result.
656
- var prevSnapshot = memoizedSnapshot;
657
- var prevSelection = memoizedSelection;
658
-
659
- if (objectIs(prevSnapshot, nextSnapshot)) {
660
- // The snapshot is the same as last time. Reuse the previous selection.
661
- return prevSelection;
662
- } // The snapshot has changed, so we need to compute a new selection.
663
-
664
-
665
- // The snapshot has changed, so we need to compute a new selection.
666
- var nextSelection = selector(nextSnapshot); // If a custom isEqual function is provided, use that to check if the data
667
- // has changed. If it hasn't, return the previous selection. That signals
668
- // to React that the selections are conceptually equal, and we can bail
669
- // out of rendering.
670
-
671
- // If a custom isEqual function is provided, use that to check if the data
672
- // has changed. If it hasn't, return the previous selection. That signals
673
- // to React that the selections are conceptually equal, and we can bail
674
- // out of rendering.
675
- if (isEqual !== undefined && isEqual(prevSelection, nextSelection)) {
676
- return prevSelection;
677
- }
678
-
679
- memoizedSnapshot = nextSnapshot;
680
- memoizedSelection = nextSelection;
681
- return nextSelection;
682
- }; // Assigning this to a constant so that Flow knows it can't change.
683
-
684
-
685
- // Assigning this to a constant so that Flow knows it can't change.
686
- var maybeGetServerSnapshot = getServerSnapshot === undefined ? null : getServerSnapshot;
687
-
688
- var getSnapshotWithSelector = function () {
689
- return memoizedSelector(getSnapshot());
690
- };
691
-
692
- var getServerSnapshotWithSelector = maybeGetServerSnapshot === null ? undefined : function () {
693
- return memoizedSelector(maybeGetServerSnapshot());
694
- };
695
- return [getSnapshotWithSelector, getServerSnapshotWithSelector];
696
- }, [getSnapshot, getServerSnapshot, selector, isEqual]),
697
- getSelection = _useMemo[0],
698
- getServerSelection = _useMemo[1];
699
-
700
- var value = useSyncExternalStore(subscribe, getSelection, getServerSelection);
701
- useEffect(function () {
702
- inst.hasValue = true;
703
- inst.value = value;
704
- }, [value]);
705
- useDebugValue(value);
706
- return value;
707
- }
708
-
709
- withSelector_development.useSyncExternalStoreWithSelector = useSyncExternalStoreWithSelector;
710
- /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
711
- if (
712
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
713
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===
714
- 'function'
715
- ) {
716
- __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
717
- }
718
-
719
- })();
720
- }
721
- return withSelector_development;
722
- }
723
-
724
- if (process.env.NODE_ENV === 'production') {
725
- withSelector.exports = requireWithSelector_production_min();
726
- } else {
727
- withSelector.exports = requireWithSelector_development();
286
+ function useEditorState(options) {
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;
728
301
  }
729
302
 
730
- var withSelectorExports = withSelector.exports;
731
-
732
- const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
733
- /**
734
- * To synchronize the editor instance with the component state,
735
- * we need to create a separate instance that is not affected by the component re-renders.
736
- */
737
- class EditorStateManager {
738
- constructor(initialEditor) {
739
- this.transactionNumber = 0;
740
- this.lastTransactionNumber = 0;
741
- this.subscribers = new Set();
742
- this.editor = initialEditor;
743
- this.lastSnapshot = { editor: initialEditor, transactionNumber: 0 };
744
- this.getSnapshot = this.getSnapshot.bind(this);
745
- this.getServerSnapshot = this.getServerSnapshot.bind(this);
746
- this.watch = this.watch.bind(this);
747
- this.subscribe = this.subscribe.bind(this);
748
- }
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) {
749
309
  /**
750
- * Get the current editor instance.
310
+ * The current editor instance.
751
311
  */
752
- getSnapshot() {
753
- if (this.transactionNumber === this.lastTransactionNumber) {
754
- return this.lastSnapshot;
755
- }
756
- this.lastTransactionNumber = this.transactionNumber;
757
- this.lastSnapshot = { editor: this.editor, transactionNumber: this.transactionNumber };
758
- return this.lastSnapshot;
759
- }
312
+ this.editor = null;
760
313
  /**
761
- * Always disable the editor on the server-side.
314
+ * The subscriptions to notify when the editor instance
315
+ * has been created or destroyed.
762
316
  */
763
- getServerSnapshot() {
764
- return { editor: null, transactionNumber: 0 };
765
- }
317
+ this.subscriptions = /* @__PURE__ */ new Set();
766
318
  /**
767
- * Subscribe to the editor instance's changes.
319
+ * Whether the editor has been mounted.
768
320
  */
769
- subscribe(callback) {
770
- this.subscribers.add(callback);
771
- return () => {
772
- this.subscribers.delete(callback);
773
- };
774
- }
775
- /**
776
- * Watch the editor instance for changes.
777
- */
778
- watch(nextEditor) {
779
- this.editor = nextEditor;
780
- if (this.editor) {
781
- /**
782
- * This will force a re-render when the editor state changes.
783
- * This is to support things like `editor.can().toggleBold()` in components that `useEditor`.
784
- * This could be more efficient, but it's a good trade-off for now.
785
- */
786
- const fn = () => {
787
- this.transactionNumber += 1;
788
- this.subscribers.forEach(callback => callback());
789
- };
790
- const currentEditor = this.editor;
791
- currentEditor.on('transaction', fn);
792
- return () => {
793
- currentEditor.off('transaction', fn);
794
- };
795
- }
796
- return undefined;
797
- }
798
- }
799
- /**
800
- * This hook allows you to watch for changes on the editor instance.
801
- * It will allow you to select a part of the editor state and re-render the component when it changes.
802
- * @example
803
- * ```tsx
804
- * const editor = useEditor({...options})
805
- * const { currentSelection } = useEditorState({
806
- * editor,
807
- * selector: snapshot => ({ currentSelection: snapshot.editor.state.selection }),
808
- * })
809
- */
810
- function useEditorState(options) {
811
- var _a;
812
- const [editorStateManager] = React.useState(() => new EditorStateManager(options.editor));
813
- // Using the `useSyncExternalStore` hook to sync the editor instance with the component state
814
- const selectedState = withSelectorExports.useSyncExternalStoreWithSelector(editorStateManager.subscribe, editorStateManager.getSnapshot, editorStateManager.getServerSnapshot, options.selector, (_a = options.equalityFn) !== null && _a !== void 0 ? _a : deepEqual);
815
- useIsomorphicLayoutEffect(() => {
816
- return editorStateManager.watch(options.editor);
817
- }, [options.editor, editorStateManager]);
818
- React.useDebugValue(selectedState);
819
- return selectedState;
820
- }
821
-
822
- const isDev = process.env.NODE_ENV !== 'production';
823
- const isSSR = typeof window === 'undefined';
824
- const isNext = isSSR || Boolean(typeof window !== 'undefined' && window.next);
825
- /**
826
- * This class handles the creation, destruction, and re-creation of the editor instance.
827
- */
828
- class EditorInstanceManager {
829
- constructor(options) {
830
- /**
831
- * The current editor instance.
832
- */
833
- this.editor = null;
834
- /**
835
- * The subscriptions to notify when the editor instance
836
- * has been created or destroyed.
837
- */
838
- this.subscriptions = new Set();
839
- /**
840
- * Whether the editor has been mounted.
841
- */
842
- this.isComponentMounted = false;
843
- /**
844
- * The most recent dependencies array.
845
- */
846
- this.previousDeps = null;
847
- /**
848
- * The unique instance ID. This is used to identify the editor instance. And will be re-generated for each new instance.
849
- */
850
- this.instanceId = '';
851
- this.options = options;
852
- this.subscriptions = new Set();
853
- this.setEditor(this.getInitialEditor());
854
- this.scheduleDestroy();
855
- this.getEditor = this.getEditor.bind(this);
856
- this.getServerSnapshot = this.getServerSnapshot.bind(this);
857
- this.subscribe = this.subscribe.bind(this);
858
- this.refreshEditorInstance = this.refreshEditorInstance.bind(this);
859
- this.scheduleDestroy = this.scheduleDestroy.bind(this);
860
- this.onRender = this.onRender.bind(this);
861
- this.createEditor = this.createEditor.bind(this);
862
- }
863
- setEditor(editor) {
864
- this.editor = editor;
865
- this.instanceId = Math.random().toString(36).slice(2, 9);
866
- // Notify all subscribers that the editor instance has been created
867
- this.subscriptions.forEach(cb => cb());
868
- }
869
- getInitialEditor() {
870
- if (this.options.current.immediatelyRender === undefined) {
871
- if (isSSR || isNext) {
872
- // TODO in the next major release, we should throw an error here
873
- if (isDev) {
874
- /**
875
- * Throw an error in development, to make sure the developer is aware that tiptap cannot be SSR'd
876
- * and that they need to set `immediatelyRender` to `false` to avoid hydration mismatches.
877
- */
878
- console.warn('Tiptap Error: SSR has been detected, please set `immediatelyRender` explicitly to `false` to avoid hydration mismatches.');
879
- }
880
- // Best faith effort in production, run the code in the legacy mode to avoid hydration mismatches and errors in production
881
- return null;
882
- }
883
- // Default to immediately rendering when client-side rendering
884
- return this.createEditor();
885
- }
886
- if (this.options.current.immediatelyRender && isSSR && isDev) {
887
- // Warn in development, to make sure the developer is aware that tiptap cannot be SSR'd, set `immediatelyRender` to `false` to avoid hydration mismatches.
888
- 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.');
889
- }
890
- if (this.options.current.immediatelyRender) {
891
- return this.createEditor();
892
- }
893
- return null;
894
- }
321
+ this.isComponentMounted = false;
895
322
  /**
896
- * Create a new editor instance. And attach event listeners.
323
+ * The most recent dependencies array.
897
324
  */
898
- createEditor() {
899
- const optionsToApply = {
900
- ...this.options.current,
901
- // Always call the most recent version of the callback function by default
902
- onBeforeCreate: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onBeforeCreate) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
903
- onBlur: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onBlur) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
904
- onCreate: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onCreate) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
905
- onDestroy: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onDestroy) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
906
- onFocus: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onFocus) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
907
- onSelectionUpdate: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onSelectionUpdate) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
908
- onTransaction: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onTransaction) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
909
- onUpdate: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onUpdate) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
910
- onContentError: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onContentError) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
911
- onDrop: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onDrop) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
912
- onPaste: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onPaste) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
913
- };
914
- const editor = new core.Editor(optionsToApply);
915
- // no need to keep track of the event listeners, they will be removed when the editor is destroyed
916
- return editor;
917
- }
325
+ this.previousDeps = null;
918
326
  /**
919
- * Get the current editor instance.
327
+ * The unique instance ID. This is used to identify the editor instance. And will be re-generated for each new instance.
920
328
  */
921
- getEditor() {
922
- return this.editor;
923
- }
924
- /**
925
- * Always disable the editor on the server-side.
926
- */
927
- getServerSnapshot() {
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
+ }
928
355
  return null;
356
+ }
357
+ return this.createEditor();
929
358
  }
930
- /**
931
- * Subscribe to the editor instance's changes.
932
- */
933
- subscribe(onStoreChange) {
934
- this.subscriptions.add(onStoreChange);
935
- return () => {
936
- this.subscriptions.delete(onStoreChange);
937
- };
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
+ );
938
363
  }
939
- static compareOptions(a, b) {
940
- return Object.keys(a).every(key => {
941
- if (['onCreate', 'onBeforeCreate', 'onDestroy', 'onUpdate', 'onTransaction', 'onFocus', 'onBlur', 'onSelectionUpdate', 'onContentError', 'onDrop', 'onPaste'].includes(key)) {
942
- // we don't want to compare callbacks, they are always different and only registered once
943
- return true;
944
- }
945
- // We often encourage putting extensions inlined in the options object, so we will do a slightly deeper comparison here
946
- if (key === 'extensions' && a.extensions && b.extensions) {
947
- if (a.extensions.length !== b.extensions.length) {
948
- return false;
949
- }
950
- return a.extensions.every((extension, index) => {
951
- var _a;
952
- if (extension !== ((_a = b.extensions) === null || _a === void 0 ? void 0 : _a[index])) {
953
- return false;
954
- }
955
- return true;
956
- });
957
- }
958
- if (a[key] !== b[key]) {
959
- // if any of the options have changed, we should update the editor options
960
- return false;
961
- }
962
- return true;
963
- });
364
+ if (this.options.current.immediatelyRender) {
365
+ return this.createEditor();
964
366
  }
965
- /**
966
- * On each render, we will create, update, or destroy the editor instance.
967
- * @param deps The dependencies to watch for changes
968
- * @returns A cleanup function
969
- */
970
- onRender(deps) {
971
- // The returned callback will run on each render
972
- return () => {
973
- this.isComponentMounted = true;
974
- // Cleanup any scheduled destructions, since we are currently rendering
975
- clearTimeout(this.scheduledDestructionTimeout);
976
- if (this.editor && !this.editor.isDestroyed && deps.length === 0) {
977
- // if the editor does exist & deps are empty, we don't need to re-initialize the editor generally
978
- if (!EditorInstanceManager.compareOptions(this.options.current, this.editor.options)) {
979
- // But, the options are different, so we need to update the editor options
980
- // Still, this is faster than re-creating the editor
981
- this.editor.setOptions({
982
- ...this.options.current,
983
- editable: this.editor.isEditable,
984
- });
985
- }
986
- }
987
- else {
988
- // When the editor:
989
- // - does not yet exist
990
- // - is destroyed
991
- // - the deps array changes
992
- // We need to destroy the editor instance and re-initialize it
993
- this.refreshEditorInstance(deps);
994
- }
995
- return () => {
996
- this.isComponentMounted = false;
997
- this.scheduleDestroy();
998
- };
999
- };
1000
- }
1001
- /**
1002
- * Recreate the editor instance if the dependencies have changed.
1003
- */
1004
- refreshEditorInstance(deps) {
1005
- if (this.editor && !this.editor.isDestroyed) {
1006
- // Editor instance already exists
1007
- if (this.previousDeps === null) {
1008
- // If lastDeps has not yet been initialized, reuse the current editor instance
1009
- this.previousDeps = deps;
1010
- return;
1011
- }
1012
- const depsAreEqual = this.previousDeps.length === deps.length
1013
- && this.previousDeps.every((dep, index) => dep === deps[index]);
1014
- if (depsAreEqual) {
1015
- // deps exist and are equal, no need to recreate
1016
- return;
1017
- }
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;
1018
469
  }
1019
- if (this.editor && !this.editor.isDestroyed) {
1020
- // Destroy the editor instance if it exists
1021
- this.editor.destroy();
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;
476
+ });
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
+ });
1022
499
  }
1023
- this.setEditor(this.createEditor());
1024
- // Update the lastDeps to the current deps
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) {
1025
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
+ }
1026
522
  }
1027
- /**
1028
- * Schedule the destruction of the editor instance.
1029
- * This will only destroy the editor if it was not mounted on the next tick.
1030
- * This is to avoid destroying the editor instance when it's actually still mounted.
1031
- */
1032
- scheduleDestroy() {
1033
- const currentInstanceId = this.instanceId;
1034
- const currentEditor = this.editor;
1035
- // Wait two ticks to see if the component is still mounted
1036
- this.scheduledDestructionTimeout = setTimeout(() => {
1037
- if (this.isComponentMounted && this.instanceId === currentInstanceId) {
1038
- // If still mounted on the following tick, with the same instanceId, do not destroy the editor
1039
- if (currentEditor) {
1040
- // just re-apply options as they might have changed
1041
- currentEditor.setOptions(this.options.current);
1042
- }
1043
- return;
1044
- }
1045
- if (currentEditor && !currentEditor.isDestroyed) {
1046
- currentEditor.destroy();
1047
- if (this.instanceId === currentInstanceId) {
1048
- this.setEditor(null);
1049
- }
1050
- }
1051
- // This allows the effect to run again between ticks
1052
- // which may save us from having to re-create the editor
1053
- }, 1);
523
+ if (this.editor && !this.editor.isDestroyed) {
524
+ this.editor.destroy();
1054
525
  }
1055
- }
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);
541
+ }
542
+ return;
543
+ }
544
+ if (currentEditor && !currentEditor.isDestroyed) {
545
+ currentEditor.destroy();
546
+ if (this.instanceId === currentInstanceId) {
547
+ this.setEditor(null);
548
+ }
549
+ }
550
+ }, 1);
551
+ }
552
+ };
1056
553
  function useEditor(options = {}, deps = []) {
1057
- const mostRecentOptions = React.useRef(options);
1058
- mostRecentOptions.current = options;
1059
- const [instanceManager] = React.useState(() => new EditorInstanceManager(mostRecentOptions));
1060
- const editor = shimExports.useSyncExternalStore(instanceManager.subscribe, instanceManager.getEditor, instanceManager.getServerSnapshot);
1061
- React.useDebugValue(editor);
1062
- // This effect will handle creating/updating the editor instance
1063
- // eslint-disable-next-line react-hooks/exhaustive-deps
1064
- React.useEffect(instanceManager.onRender(deps));
1065
- // The default behavior is to re-render on each transaction
1066
- // This is legacy behavior that will be removed in future versions
1067
- useEditorState({
1068
- editor,
1069
- selector: ({ transactionNumber }) => {
1070
- if (options.shouldRerenderOnTransaction === false) {
1071
- // This will prevent the editor from re-rendering on each transaction
1072
- return null;
1073
- }
1074
- // This will avoid re-rendering on the first transaction when `immediatelyRender` is set to `true`
1075
- if (options.immediatelyRender && transactionNumber === 0) {
1076
- return 0;
1077
- }
1078
- return transactionNumber + 1;
1079
- },
1080
- });
1081
- return editor;
1082
- }
1083
-
1084
- const EditorContext = React.createContext({
1085
- editor: null,
1086
- });
1087
- const EditorConsumer = EditorContext.Consumer;
1088
- /**
1089
- * A hook to get the current editor instance.
1090
- */
1091
- const useCurrentEditor = () => React.useContext(EditorContext);
1092
- /**
1093
- * This is the provider component for the editor.
1094
- * It allows the editor to be accessible across the entire component tree
1095
- * with `useCurrentEditor`.
1096
- */
1097
- function EditorProvider({ children, slotAfter, slotBefore, editorContainerProps = {}, ...editorOptions }) {
1098
- const editor = useEditor(editorOptions);
1099
- if (!editor) {
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) {
1100
568
  return null;
569
+ }
570
+ if (options.immediatelyRender && transactionNumber === 0) {
571
+ return 0;
572
+ }
573
+ return transactionNumber + 1;
1101
574
  }
1102
- return (React__default.default.createElement(EditorContext.Provider, { value: { editor } },
1103
- slotBefore,
1104
- React__default.default.createElement(EditorConsumer, null, ({ editor: currentEditor }) => (React__default.default.createElement(EditorContent, { editor: currentEditor, ...editorContainerProps }))),
1105
- children,
1106
- slotAfter));
575
+ });
576
+ return editor;
1107
577
  }
1108
578
 
1109
- const BubbleMenu = (props) => {
1110
- const [element, setElement] = React.useState(null);
1111
- const { editor: currentEditor } = useCurrentEditor();
1112
- React.useEffect(() => {
1113
- var _a;
1114
- if (!element) {
1115
- return;
1116
- }
1117
- if (((_a = props.editor) === null || _a === void 0 ? void 0 : _a.isDestroyed) || (currentEditor === null || currentEditor === void 0 ? void 0 : currentEditor.isDestroyed)) {
1118
- return;
1119
- }
1120
- const { pluginKey = 'bubbleMenu', editor, tippyOptions = {}, updateDelay, shouldShow = null, } = props;
1121
- const menuEditor = editor || currentEditor;
1122
- if (!menuEditor) {
1123
- console.warn('BubbleMenu component is not rendered inside of an editor component or does not have editor prop.');
1124
- return;
1125
- }
1126
- const plugin = extensionBubbleMenu.BubbleMenuPlugin({
1127
- updateDelay,
1128
- editor: menuEditor,
1129
- element,
1130
- pluginKey,
1131
- shouldShow,
1132
- tippyOptions,
1133
- });
1134
- menuEditor.registerPlugin(plugin);
1135
- return () => { menuEditor.unregisterPlugin(pluginKey); };
1136
- }, [props.editor, currentEditor, element]);
1137
- return (React__default.default.createElement("div", { ref: setElement, className: props.className, style: { visibility: 'hidden' } }, props.children));
1138
- };
1139
-
1140
- const FloatingMenu = (props) => {
1141
- const [element, setElement] = React.useState(null);
1142
- const { editor: currentEditor } = useCurrentEditor();
1143
- React.useEffect(() => {
1144
- var _a;
1145
- if (!element) {
1146
- return;
1147
- }
1148
- if (((_a = props.editor) === null || _a === void 0 ? void 0 : _a.isDestroyed) || (currentEditor === null || currentEditor === void 0 ? void 0 : currentEditor.isDestroyed)) {
1149
- return;
1150
- }
1151
- const { pluginKey = 'floatingMenu', editor, tippyOptions = {}, shouldShow = null, } = props;
1152
- const menuEditor = editor || currentEditor;
1153
- if (!menuEditor) {
1154
- console.warn('FloatingMenu component is not rendered inside of an editor component or does not have editor prop.');
1155
- return;
1156
- }
1157
- const plugin = extensionFloatingMenu.FloatingMenuPlugin({
1158
- pluginKey,
1159
- editor: menuEditor,
1160
- element,
1161
- tippyOptions,
1162
- shouldShow,
1163
- });
1164
- menuEditor.registerPlugin(plugin);
1165
- return () => { menuEditor.unregisterPlugin(pluginKey); };
1166
- }, [
1167
- props.editor,
1168
- currentEditor,
1169
- element,
1170
- ]);
1171
- return (React__default.default.createElement("div", { ref: setElement, className: props.className, style: { visibility: 'hidden' } }, props.children));
1172
- };
1173
-
1174
- const ReactNodeViewContext = React.createContext({
1175
- 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
1176
583
  });
1177
- 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
+ }
1178
605
 
1179
- const NodeViewContent = props => {
1180
- const Tag = props.as || 'div';
1181
- const { nodeViewContentRef } = useReactNodeView();
1182
- return (
1183
- // @ts-ignore
1184
- React__default.default.createElement(Tag, { ...props, ref: nodeViewContentRef, "data-node-view-content": "", style: {
1185
- whiteSpace: 'pre-wrap',
1186
- ...props.style,
1187
- } }));
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);
1188
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
+ }
1189
644
 
1190
- const NodeViewWrapper = React__default.default.forwardRef((props, ref) => {
1191
- const { onDragStart } = useReactNodeView();
1192
- const Tag = props.as || 'div';
1193
- return (
1194
- // @ts-ignore
1195
- React__default.default.createElement(Tag, { ...props, ref: ref, "data-node-view-wrapper": "", onDragStart: onDragStart, style: {
1196
- whiteSpace: 'normal',
1197
- ...props.style,
1198
- } }));
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
+ );
1199
667
  });
1200
668
 
1201
- /**
1202
- * Check if a component is a class component.
1203
- * @param Component
1204
- * @returns {boolean}
1205
- */
669
+ // src/ReactMarkViewRenderer.tsx
670
+ var import_core2 = require("@tiptap/core");
671
+ var import_react8 = __toESM(require("react"), 1);
672
+
673
+ // src/ReactRenderer.tsx
674
+ var import_react_dom2 = require("react-dom");
675
+ var import_jsx_runtime5 = require("react/jsx-runtime");
1206
676
  function isClassComponent(Component) {
1207
- return !!(typeof Component === 'function'
1208
- && Component.prototype
1209
- && Component.prototype.isReactComponent);
677
+ return !!(typeof Component === "function" && Component.prototype && Component.prototype.isReactComponent);
1210
678
  }
1211
- /**
1212
- * Check if a component is a forward ref component.
1213
- * @param Component
1214
- * @returns {boolean}
1215
- */
1216
679
  function isForwardRefComponent(Component) {
1217
- var _a;
1218
- return !!(typeof Component === 'object'
1219
- && ((_a = Component.$$typeof) === null || _a === void 0 ? void 0 : _a.toString()) === 'Symbol(react.forward_ref)');
680
+ var _a;
681
+ return !!(typeof Component === "object" && ((_a = Component.$$typeof) == null ? void 0 : _a.toString()) === "Symbol(react.forward_ref)");
1220
682
  }
1221
- /**
1222
- * The ReactRenderer class. It's responsible for rendering React components inside the editor.
1223
- * @example
1224
- * new ReactRenderer(MyComponent, {
1225
- * editor,
1226
- * props: {
1227
- * foo: 'bar',
1228
- * },
1229
- * as: 'span',
1230
- * })
1231
- */
1232
- class ReactRenderer {
1233
- /**
1234
- * Immediately creates element and renders the provided React component.
1235
- */
1236
- constructor(component, { editor, props = {}, as = 'div', className = '', }) {
1237
- this.ref = null;
1238
- this.id = Math.floor(Math.random() * 0xFFFFFFFF).toString();
1239
- this.component = component;
1240
- this.editor = editor;
1241
- this.props = props;
1242
- this.element = document.createElement(as);
1243
- this.element.classList.add('react-renderer');
1244
- if (className) {
1245
- this.element.classList.add(...className.split(' '));
1246
- }
1247
- if (this.editor.isInitialized) {
1248
- // On first render, we need to flush the render synchronously
1249
- // Renders afterwards can be async, but this fixes a cursor positioning issue
1250
- ReactDOM.flushSync(() => {
1251
- this.render();
1252
- });
1253
- }
1254
- else {
1255
- this.render();
1256
- }
683
+ var ReactRenderer = class {
684
+ /**
685
+ * Immediately creates element and renders the provided React component.
686
+ */
687
+ constructor(component, { editor, props = {}, as = "div", className = "" }) {
688
+ this.ref = null;
689
+ this.id = Math.floor(Math.random() * 4294967295).toString();
690
+ this.component = component;
691
+ this.editor = editor;
692
+ this.props = props;
693
+ this.element = document.createElement(as);
694
+ this.element.classList.add("react-renderer");
695
+ if (className) {
696
+ this.element.classList.add(...className.split(" "));
1257
697
  }
1258
- /**
1259
- * Render the React component.
1260
- */
1261
- render() {
1262
- var _a;
1263
- const Component = this.component;
1264
- const props = this.props;
1265
- const editor = this.editor;
1266
- if (isClassComponent(Component) || isForwardRefComponent(Component)) {
1267
- // @ts-ignore This is a hack to make the ref work
1268
- props.ref = (ref) => {
1269
- this.ref = ref;
1270
- };
1271
- }
1272
- this.reactElement = React__default.default.createElement(Component, { ...props });
1273
- (_a = editor === null || editor === void 0 ? void 0 : editor.contentComponent) === null || _a === void 0 ? void 0 : _a.setRenderer(this.id, this);
1274
- }
1275
- /**
1276
- * Re-renders the React component with new props.
1277
- */
1278
- updateProps(props = {}) {
1279
- this.props = {
1280
- ...this.props,
1281
- ...props,
1282
- };
698
+ if (this.editor.isInitialized) {
699
+ (0, import_react_dom2.flushSync)(() => {
1283
700
  this.render();
701
+ });
702
+ } else {
703
+ this.render();
1284
704
  }
1285
- /**
1286
- * Destroy the React component.
1287
- */
1288
- destroy() {
1289
- var _a;
1290
- const editor = this.editor;
1291
- (_a = editor === null || editor === void 0 ? void 0 : editor.contentComponent) === null || _a === void 0 ? void 0 : _a.removeRenderer(this.id);
705
+ }
706
+ /**
707
+ * Render the React component.
708
+ */
709
+ render() {
710
+ var _a;
711
+ const Component = this.component;
712
+ const props = this.props;
713
+ const editor = this.editor;
714
+ if (isClassComponent(Component) || isForwardRefComponent(Component)) {
715
+ props.ref = (ref) => {
716
+ this.ref = ref;
717
+ };
1292
718
  }
1293
- /**
1294
- * Update the attributes of the element that holds the React component.
1295
- */
1296
- updateAttributes(attributes) {
1297
- Object.keys(attributes).forEach(key => {
1298
- this.element.setAttribute(key, attributes[key]);
1299
- });
719
+ this.reactElement = /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Component, { ...props });
720
+ (_a = editor == null ? void 0 : editor.contentComponent) == null ? void 0 : _a.setRenderer(this.id, this);
721
+ }
722
+ /**
723
+ * Re-renders the React component with new props.
724
+ */
725
+ updateProps(props = {}) {
726
+ this.props = {
727
+ ...this.props,
728
+ ...props
729
+ };
730
+ this.render();
731
+ }
732
+ /**
733
+ * Destroy the React component.
734
+ */
735
+ destroy() {
736
+ var _a;
737
+ const editor = this.editor;
738
+ (_a = editor == null ? void 0 : editor.contentComponent) == null ? void 0 : _a.removeRenderer(this.id);
739
+ }
740
+ /**
741
+ * Update the attributes of the element that holds the React component.
742
+ */
743
+ updateAttributes(attributes) {
744
+ Object.keys(attributes).forEach((key) => {
745
+ this.element.setAttribute(key, attributes[key]);
746
+ });
747
+ }
748
+ };
749
+
750
+ // src/ReactMarkViewRenderer.tsx
751
+ var import_jsx_runtime6 = (
752
+ // @ts-ignore
753
+ require("react/jsx-runtime")
754
+ );
755
+ var ReactMarkViewContext = import_react8.default.createContext({
756
+ markViewContentRef: () => {
757
+ }
758
+ });
759
+ var MarkViewContent = (props) => {
760
+ const Tag = props.as || "span";
761
+ const { markViewContentRef } = import_react8.default.useContext(ReactMarkViewContext);
762
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Tag, { ...props, ref: markViewContentRef, "data-mark-view-content": "" });
763
+ };
764
+ var ReactMarkView = class extends import_core2.MarkView {
765
+ constructor(component, props, options) {
766
+ super(component, props, options);
767
+ this.didMountContentDomElement = false;
768
+ const { as = "span", attrs, className = "" } = options || {};
769
+ const componentProps = props;
770
+ this.contentDOMElement = document.createElement("span");
771
+ const markViewContentRef = (el) => {
772
+ if (el && this.contentDOMElement && el.firstChild !== this.contentDOMElement) {
773
+ el.appendChild(this.contentDOMElement);
774
+ this.didMountContentDomElement = true;
775
+ }
776
+ };
777
+ const context = {
778
+ markViewContentRef
779
+ };
780
+ const ReactMarkViewProvider = import_react8.default.memo((componentProps2) => {
781
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(ReactMarkViewContext.Provider, { value: context, children: import_react8.default.createElement(component, componentProps2) });
782
+ });
783
+ ReactMarkViewProvider.displayName = "ReactNodeView";
784
+ this.renderer = new ReactRenderer(ReactMarkViewProvider, {
785
+ editor: props.editor,
786
+ props: componentProps,
787
+ as,
788
+ className: `mark-${props.mark.type.name} ${className}`.trim()
789
+ });
790
+ if (attrs) {
791
+ this.renderer.updateAttributes(attrs);
1300
792
  }
793
+ }
794
+ get dom() {
795
+ return this.renderer.element;
796
+ }
797
+ get contentDOM() {
798
+ if (!this.didMountContentDomElement) {
799
+ return null;
800
+ }
801
+ return this.contentDOMElement;
802
+ }
803
+ };
804
+ function ReactMarkViewRenderer(component, options = {}) {
805
+ return (props) => new ReactMarkView(component, props, options);
1301
806
  }
1302
807
 
1303
- class ReactNodeView extends core.NodeView {
1304
- /**
1305
- * Setup the React component.
1306
- * Called on initialization.
1307
- */
1308
- mount() {
1309
- const props = {
1310
- editor: this.editor,
1311
- node: this.node,
1312
- decorations: this.decorations,
1313
- innerDecorations: this.innerDecorations,
1314
- view: this.view,
1315
- selected: false,
1316
- extension: this.extension,
1317
- HTMLAttributes: this.HTMLAttributes,
1318
- getPos: () => this.getPos(),
1319
- updateAttributes: (attributes = {}) => this.updateAttributes(attributes),
1320
- deleteNode: () => this.deleteNode(),
1321
- };
1322
- if (!this.component.displayName) {
1323
- const capitalizeFirstChar = (string) => {
1324
- return string.charAt(0).toUpperCase() + string.substring(1);
1325
- };
1326
- this.component.displayName = capitalizeFirstChar(this.extension.name);
1327
- }
1328
- const onDragStart = this.onDragStart.bind(this);
1329
- const nodeViewContentRef = element => {
1330
- if (element && this.contentDOMElement && element.firstChild !== this.contentDOMElement) {
1331
- element.appendChild(this.contentDOMElement);
1332
- }
1333
- };
1334
- const context = { onDragStart, nodeViewContentRef };
1335
- const Component = this.component;
1336
- // For performance reasons, we memoize the provider component
1337
- // And all of the things it requires are declared outside of the component, so it doesn't need to re-render
1338
- const ReactNodeViewProvider = React__default.default.memo(componentProps => {
1339
- return (React__default.default.createElement(ReactNodeViewContext.Provider, { value: context }, React__default.default.createElement(Component, componentProps)));
1340
- });
1341
- ReactNodeViewProvider.displayName = 'ReactNodeView';
1342
- if (this.node.isLeaf) {
1343
- this.contentDOMElement = null;
1344
- }
1345
- else if (this.options.contentDOMElementTag) {
1346
- this.contentDOMElement = document.createElement(this.options.contentDOMElementTag);
1347
- }
1348
- else {
1349
- this.contentDOMElement = document.createElement(this.node.isInline ? 'span' : 'div');
1350
- }
1351
- if (this.contentDOMElement) {
1352
- this.contentDOMElement.dataset.nodeViewContentReact = '';
1353
- // For some reason the whiteSpace prop is not inherited properly in Chrome and Safari
1354
- // With this fix it seems to work fine
1355
- // See: https://github.com/ueberdosis/tiptap/issues/1197
1356
- this.contentDOMElement.style.whiteSpace = 'inherit';
1357
- }
1358
- let as = this.node.isInline ? 'span' : 'div';
1359
- if (this.options.as) {
1360
- as = this.options.as;
1361
- }
1362
- const { className = '' } = this.options;
1363
- this.handleSelectionUpdate = this.handleSelectionUpdate.bind(this);
1364
- this.renderer = new ReactRenderer(ReactNodeViewProvider, {
1365
- editor: this.editor,
1366
- props,
1367
- as,
1368
- className: `node-${this.node.type.name} ${className}`.trim(),
1369
- });
1370
- this.editor.on('selectionUpdate', this.handleSelectionUpdate);
1371
- this.updateElementAttributes();
808
+ // src/ReactNodeViewRenderer.tsx
809
+ var import_core3 = require("@tiptap/core");
810
+ var import_react9 = __toESM(require("react"), 1);
811
+ var import_jsx_runtime7 = require("react/jsx-runtime");
812
+ var ReactNodeView = class extends import_core3.NodeView {
813
+ /**
814
+ * Setup the React component.
815
+ * Called on initialization.
816
+ */
817
+ mount() {
818
+ const props = {
819
+ editor: this.editor,
820
+ node: this.node,
821
+ decorations: this.decorations,
822
+ innerDecorations: this.innerDecorations,
823
+ view: this.view,
824
+ selected: false,
825
+ extension: this.extension,
826
+ HTMLAttributes: this.HTMLAttributes,
827
+ getPos: () => this.getPos(),
828
+ updateAttributes: (attributes = {}) => this.updateAttributes(attributes),
829
+ deleteNode: () => this.deleteNode()
830
+ };
831
+ if (!this.component.displayName) {
832
+ const capitalizeFirstChar = (string) => {
833
+ return string.charAt(0).toUpperCase() + string.substring(1);
834
+ };
835
+ this.component.displayName = capitalizeFirstChar(this.extension.name);
1372
836
  }
1373
- /**
1374
- * Return the DOM element.
1375
- * This is the element that will be used to display the node view.
1376
- */
1377
- get dom() {
1378
- var _a;
1379
- if (this.renderer.element.firstElementChild
1380
- && !((_a = this.renderer.element.firstElementChild) === null || _a === void 0 ? void 0 : _a.hasAttribute('data-node-view-wrapper'))) {
1381
- throw Error('Please use the NodeViewWrapper component for your node view.');
1382
- }
1383
- return this.renderer.element;
837
+ const onDragStart = this.onDragStart.bind(this);
838
+ const nodeViewContentRef = (element) => {
839
+ if (element && this.contentDOMElement && element.firstChild !== this.contentDOMElement) {
840
+ element.appendChild(this.contentDOMElement);
841
+ }
842
+ };
843
+ const context = { onDragStart, nodeViewContentRef };
844
+ const Component = this.component;
845
+ const ReactNodeViewProvider = import_react9.default.memo((componentProps) => {
846
+ return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(ReactNodeViewContext.Provider, { value: context, children: import_react9.default.createElement(Component, componentProps) });
847
+ });
848
+ ReactNodeViewProvider.displayName = "ReactNodeView";
849
+ if (this.node.isLeaf) {
850
+ this.contentDOMElement = null;
851
+ } else if (this.options.contentDOMElementTag) {
852
+ this.contentDOMElement = document.createElement(this.options.contentDOMElementTag);
853
+ } else {
854
+ this.contentDOMElement = document.createElement(this.node.isInline ? "span" : "div");
1384
855
  }
1385
- /**
1386
- * Return the content DOM element.
1387
- * This is the element that will be used to display the rich-text content of the node.
1388
- */
1389
- get contentDOM() {
1390
- if (this.node.isLeaf) {
1391
- return null;
1392
- }
1393
- return this.contentDOMElement;
856
+ if (this.contentDOMElement) {
857
+ this.contentDOMElement.dataset.nodeViewContentReact = "";
858
+ this.contentDOMElement.style.whiteSpace = "inherit";
1394
859
  }
1395
- /**
1396
- * On editor selection update, check if the node is selected.
1397
- * If it is, call `selectNode`, otherwise call `deselectNode`.
1398
- */
1399
- handleSelectionUpdate() {
1400
- const { from, to } = this.editor.state.selection;
1401
- const pos = this.getPos();
1402
- if (typeof pos !== 'number') {
1403
- return;
1404
- }
1405
- if (from <= pos && to >= pos + this.node.nodeSize) {
1406
- if (this.renderer.props.selected) {
1407
- return;
1408
- }
1409
- this.selectNode();
1410
- }
1411
- else {
1412
- if (!this.renderer.props.selected) {
1413
- return;
1414
- }
1415
- this.deselectNode();
1416
- }
860
+ let as = this.node.isInline ? "span" : "div";
861
+ if (this.options.as) {
862
+ as = this.options.as;
1417
863
  }
1418
- /**
1419
- * On update, update the React component.
1420
- * To prevent unnecessary updates, the `update` option can be used.
1421
- */
1422
- update(node, decorations, innerDecorations) {
1423
- const rerenderComponent = (props) => {
1424
- this.renderer.updateProps(props);
1425
- if (typeof this.options.attrs === 'function') {
1426
- this.updateElementAttributes();
1427
- }
1428
- };
1429
- if (node.type !== this.node.type) {
1430
- return false;
1431
- }
1432
- if (typeof this.options.update === 'function') {
1433
- const oldNode = this.node;
1434
- const oldDecorations = this.decorations;
1435
- const oldInnerDecorations = this.innerDecorations;
1436
- this.node = node;
1437
- this.decorations = decorations;
1438
- this.innerDecorations = innerDecorations;
1439
- return this.options.update({
1440
- oldNode,
1441
- oldDecorations,
1442
- newNode: node,
1443
- newDecorations: decorations,
1444
- oldInnerDecorations,
1445
- innerDecorations,
1446
- updateProps: () => rerenderComponent({ node, decorations, innerDecorations }),
1447
- });
1448
- }
1449
- if (node === this.node
1450
- && this.decorations === decorations
1451
- && this.innerDecorations === innerDecorations) {
1452
- return true;
1453
- }
1454
- this.node = node;
1455
- this.decorations = decorations;
1456
- this.innerDecorations = innerDecorations;
1457
- rerenderComponent({ node, decorations, innerDecorations });
1458
- return true;
864
+ const { className = "" } = this.options;
865
+ this.handleSelectionUpdate = this.handleSelectionUpdate.bind(this);
866
+ this.renderer = new ReactRenderer(ReactNodeViewProvider, {
867
+ editor: this.editor,
868
+ props,
869
+ as,
870
+ className: `node-${this.node.type.name} ${className}`.trim()
871
+ });
872
+ this.editor.on("selectionUpdate", this.handleSelectionUpdate);
873
+ this.updateElementAttributes();
874
+ }
875
+ /**
876
+ * Return the DOM element.
877
+ * This is the element that will be used to display the node view.
878
+ */
879
+ get dom() {
880
+ var _a;
881
+ if (this.renderer.element.firstElementChild && !((_a = this.renderer.element.firstElementChild) == null ? void 0 : _a.hasAttribute("data-node-view-wrapper"))) {
882
+ throw Error("Please use the NodeViewWrapper component for your node view.");
1459
883
  }
1460
- /**
1461
- * Select the node.
1462
- * Add the `selected` prop and the `ProseMirror-selectednode` class.
1463
- */
1464
- selectNode() {
1465
- this.renderer.updateProps({
1466
- selected: true,
1467
- });
1468
- this.renderer.element.classList.add('ProseMirror-selectednode');
884
+ return this.renderer.element;
885
+ }
886
+ /**
887
+ * Return the content DOM element.
888
+ * This is the element that will be used to display the rich-text content of the node.
889
+ */
890
+ get contentDOM() {
891
+ if (this.node.isLeaf) {
892
+ return null;
1469
893
  }
1470
- /**
1471
- * Deselect the node.
1472
- * Remove the `selected` prop and the `ProseMirror-selectednode` class.
1473
- */
1474
- deselectNode() {
1475
- this.renderer.updateProps({
1476
- selected: false,
1477
- });
1478
- this.renderer.element.classList.remove('ProseMirror-selectednode');
894
+ return this.contentDOMElement;
895
+ }
896
+ /**
897
+ * On editor selection update, check if the node is selected.
898
+ * If it is, call `selectNode`, otherwise call `deselectNode`.
899
+ */
900
+ handleSelectionUpdate() {
901
+ const { from, to } = this.editor.state.selection;
902
+ const pos = this.getPos();
903
+ if (typeof pos !== "number") {
904
+ return;
1479
905
  }
1480
- /**
1481
- * Destroy the React component instance.
1482
- */
1483
- destroy() {
1484
- this.renderer.destroy();
1485
- this.editor.off('selectionUpdate', this.handleSelectionUpdate);
1486
- this.contentDOMElement = null;
906
+ if (from <= pos && to >= pos + this.node.nodeSize) {
907
+ if (this.renderer.props.selected) {
908
+ return;
909
+ }
910
+ this.selectNode();
911
+ } else {
912
+ if (!this.renderer.props.selected) {
913
+ return;
914
+ }
915
+ this.deselectNode();
1487
916
  }
1488
- /**
1489
- * Update the attributes of the top-level element that holds the React component.
1490
- * Applying the attributes defined in the `attrs` option.
1491
- */
1492
- updateElementAttributes() {
1493
- if (this.options.attrs) {
1494
- let attrsObj = {};
1495
- if (typeof this.options.attrs === 'function') {
1496
- const extensionAttributes = this.editor.extensionManager.attributes;
1497
- const HTMLAttributes = core.getRenderedAttributes(this.node, extensionAttributes);
1498
- attrsObj = this.options.attrs({ node: this.node, HTMLAttributes });
1499
- }
1500
- else {
1501
- attrsObj = this.options.attrs;
1502
- }
1503
- this.renderer.updateAttributes(attrsObj);
1504
- }
917
+ }
918
+ /**
919
+ * On update, update the React component.
920
+ * To prevent unnecessary updates, the `update` option can be used.
921
+ */
922
+ update(node, decorations, innerDecorations) {
923
+ const rerenderComponent = (props) => {
924
+ this.renderer.updateProps(props);
925
+ if (typeof this.options.attrs === "function") {
926
+ this.updateElementAttributes();
927
+ }
928
+ };
929
+ if (node.type !== this.node.type) {
930
+ return false;
1505
931
  }
1506
- }
1507
- /**
1508
- * Create a React node view renderer.
1509
- */
932
+ if (typeof this.options.update === "function") {
933
+ const oldNode = this.node;
934
+ const oldDecorations = this.decorations;
935
+ const oldInnerDecorations = this.innerDecorations;
936
+ this.node = node;
937
+ this.decorations = decorations;
938
+ this.innerDecorations = innerDecorations;
939
+ return this.options.update({
940
+ oldNode,
941
+ oldDecorations,
942
+ newNode: node,
943
+ newDecorations: decorations,
944
+ oldInnerDecorations,
945
+ innerDecorations,
946
+ updateProps: () => rerenderComponent({ node, decorations, innerDecorations })
947
+ });
948
+ }
949
+ if (node === this.node && this.decorations === decorations && this.innerDecorations === innerDecorations) {
950
+ return true;
951
+ }
952
+ this.node = node;
953
+ this.decorations = decorations;
954
+ this.innerDecorations = innerDecorations;
955
+ rerenderComponent({ node, decorations, innerDecorations });
956
+ return true;
957
+ }
958
+ /**
959
+ * Select the node.
960
+ * Add the `selected` prop and the `ProseMirror-selectednode` class.
961
+ */
962
+ selectNode() {
963
+ this.renderer.updateProps({
964
+ selected: true
965
+ });
966
+ this.renderer.element.classList.add("ProseMirror-selectednode");
967
+ }
968
+ /**
969
+ * Deselect the node.
970
+ * Remove the `selected` prop and the `ProseMirror-selectednode` class.
971
+ */
972
+ deselectNode() {
973
+ this.renderer.updateProps({
974
+ selected: false
975
+ });
976
+ this.renderer.element.classList.remove("ProseMirror-selectednode");
977
+ }
978
+ /**
979
+ * Destroy the React component instance.
980
+ */
981
+ destroy() {
982
+ this.renderer.destroy();
983
+ this.editor.off("selectionUpdate", this.handleSelectionUpdate);
984
+ this.contentDOMElement = null;
985
+ }
986
+ /**
987
+ * Update the attributes of the top-level element that holds the React component.
988
+ * Applying the attributes defined in the `attrs` option.
989
+ */
990
+ updateElementAttributes() {
991
+ if (this.options.attrs) {
992
+ let attrsObj = {};
993
+ if (typeof this.options.attrs === "function") {
994
+ const extensionAttributes = this.editor.extensionManager.attributes;
995
+ const HTMLAttributes = (0, import_core3.getRenderedAttributes)(this.node, extensionAttributes);
996
+ attrsObj = this.options.attrs({ node: this.node, HTMLAttributes });
997
+ } else {
998
+ attrsObj = this.options.attrs;
999
+ }
1000
+ this.renderer.updateAttributes(attrsObj);
1001
+ }
1002
+ }
1003
+ };
1510
1004
  function ReactNodeViewRenderer(component, options) {
1511
- return props => {
1512
- // try to get the parent component
1513
- // this is important for vue devtools to show the component hierarchy correctly
1514
- // maybe it’s `undefined` because <editor-content> isn’t rendered yet
1515
- if (!props.editor.contentComponent) {
1516
- return {};
1517
- }
1518
- return new ReactNodeView(component, props, options);
1519
- };
1005
+ return (props) => {
1006
+ if (!props.editor.contentComponent) {
1007
+ return {};
1008
+ }
1009
+ return new ReactNodeView(component, props, options);
1010
+ };
1520
1011
  }
1521
1012
 
1522
- exports.BubbleMenu = BubbleMenu;
1523
- exports.EditorConsumer = EditorConsumer;
1524
- exports.EditorContent = EditorContent;
1525
- exports.EditorContext = EditorContext;
1526
- exports.EditorProvider = EditorProvider;
1527
- exports.FloatingMenu = FloatingMenu;
1528
- exports.NodeViewContent = NodeViewContent;
1529
- exports.NodeViewWrapper = NodeViewWrapper;
1530
- exports.PureEditorContent = PureEditorContent;
1531
- exports.ReactNodeView = ReactNodeView;
1532
- exports.ReactNodeViewContext = ReactNodeViewContext;
1533
- exports.ReactNodeViewRenderer = ReactNodeViewRenderer;
1534
- exports.ReactRenderer = ReactRenderer;
1535
- exports.useCurrentEditor = useCurrentEditor;
1536
- exports.useEditor = useEditor;
1537
- exports.useEditorState = useEditorState;
1538
- exports.useReactNodeView = useReactNodeView;
1539
- Object.keys(core).forEach(function (k) {
1540
- if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
1541
- enumerable: true,
1542
- get: function () { return core[k]; }
1543
- });
1013
+ // src/index.ts
1014
+ __reExport(index_exports, require("@tiptap/core"), module.exports);
1015
+ // Annotate the CommonJS export names for ESM import in node:
1016
+ 0 && (module.exports = {
1017
+ EditorConsumer,
1018
+ EditorContent,
1019
+ EditorContext,
1020
+ EditorProvider,
1021
+ MarkViewContent,
1022
+ NodeViewContent,
1023
+ NodeViewWrapper,
1024
+ PureEditorContent,
1025
+ ReactMarkView,
1026
+ ReactMarkViewContext,
1027
+ ReactMarkViewRenderer,
1028
+ ReactNodeView,
1029
+ ReactNodeViewContentProvider,
1030
+ ReactNodeViewContext,
1031
+ ReactNodeViewRenderer,
1032
+ ReactRenderer,
1033
+ useCurrentEditor,
1034
+ useEditor,
1035
+ useEditorState,
1036
+ useReactNodeView,
1037
+ ...require("@tiptap/core")
1544
1038
  });
1545
- //# sourceMappingURL=index.cjs.map
1039
+ //# sourceMappingURL=index.cjs.map