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