@tiptap/react 2.5.0-pre.8 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { BubbleMenuPlugin } from '@tiptap/extension-bubble-menu';
2
- import React, { forwardRef, useRef, useState, useEffect, createContext, useContext } from 'react';
2
+ import React, { forwardRef, useState, useEffect, useDebugValue, useRef, createContext, useContext } from 'react';
3
3
  import ReactDOM, { flushSync } from 'react-dom';
4
4
  import { Editor as Editor$1, NodeView } from '@tiptap/core';
5
5
  export * from '@tiptap/core';
@@ -133,16 +133,614 @@ class Editor extends Editor$1 {
133
133
  }
134
134
  }
135
135
 
136
+ var withSelector = {exports: {}};
137
+
138
+ var withSelector_production_min = {};
139
+
140
+ var shim = {exports: {}};
141
+
142
+ var useSyncExternalStoreShim_production_min = {};
143
+
144
+ /**
145
+ * @license React
146
+ * use-sync-external-store-shim.production.min.js
147
+ *
148
+ * Copyright (c) Facebook, Inc. and its affiliates.
149
+ *
150
+ * This source code is licensed under the MIT license found in the
151
+ * LICENSE file in the root directory of this source tree.
152
+ */
153
+
154
+ var hasRequiredUseSyncExternalStoreShim_production_min;
155
+
156
+ function requireUseSyncExternalStoreShim_production_min () {
157
+ if (hasRequiredUseSyncExternalStoreShim_production_min) return useSyncExternalStoreShim_production_min;
158
+ hasRequiredUseSyncExternalStoreShim_production_min = 1;
159
+ 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}
160
+ 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;
161
+ return useSyncExternalStoreShim_production_min;
162
+ }
163
+
164
+ var useSyncExternalStoreShim_development = {};
165
+
166
+ /**
167
+ * @license React
168
+ * use-sync-external-store-shim.development.js
169
+ *
170
+ * Copyright (c) Facebook, Inc. and its affiliates.
171
+ *
172
+ * This source code is licensed under the MIT license found in the
173
+ * LICENSE file in the root directory of this source tree.
174
+ */
175
+
176
+ var hasRequiredUseSyncExternalStoreShim_development;
177
+
178
+ function requireUseSyncExternalStoreShim_development () {
179
+ if (hasRequiredUseSyncExternalStoreShim_development) return useSyncExternalStoreShim_development;
180
+ hasRequiredUseSyncExternalStoreShim_development = 1;
181
+
182
+ if (process.env.NODE_ENV !== "production") {
183
+ (function() {
184
+
185
+ /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
186
+ if (
187
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
188
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===
189
+ 'function'
190
+ ) {
191
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
192
+ }
193
+ var React$1 = React;
194
+
195
+ var ReactSharedInternals = React$1.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
196
+
197
+ function error(format) {
198
+ {
199
+ {
200
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
201
+ args[_key2 - 1] = arguments[_key2];
202
+ }
203
+
204
+ printWarning('error', format, args);
205
+ }
206
+ }
207
+ }
208
+
209
+ function printWarning(level, format, args) {
210
+ // When changing this logic, you might want to also
211
+ // update consoleWithStackDev.www.js as well.
212
+ {
213
+ var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
214
+ var stack = ReactDebugCurrentFrame.getStackAddendum();
215
+
216
+ if (stack !== '') {
217
+ format += '%s';
218
+ args = args.concat([stack]);
219
+ } // eslint-disable-next-line react-internal/safe-string-coercion
220
+
221
+
222
+ var argsWithFormat = args.map(function (item) {
223
+ return String(item);
224
+ }); // Careful: RN currently depends on this prefix
225
+
226
+ argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
227
+ // breaks IE9: https://github.com/facebook/react/issues/13610
228
+ // eslint-disable-next-line react-internal/no-production-logging
229
+
230
+ Function.prototype.apply.call(console[level], console, argsWithFormat);
231
+ }
232
+ }
233
+
234
+ /**
235
+ * inlined Object.is polyfill to avoid requiring consumers ship their own
236
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
237
+ */
238
+ function is(x, y) {
239
+ return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
240
+ ;
241
+ }
242
+
243
+ var objectIs = typeof Object.is === 'function' ? Object.is : is;
244
+
245
+ // dispatch for CommonJS interop named imports.
246
+
247
+ var useState = React$1.useState,
248
+ useEffect = React$1.useEffect,
249
+ useLayoutEffect = React$1.useLayoutEffect,
250
+ useDebugValue = React$1.useDebugValue;
251
+ var didWarnOld18Alpha = false;
252
+ var didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works
253
+ // because of a very particular set of implementation details and assumptions
254
+ // -- change any one of them and it will break. The most important assumption
255
+ // is that updates are always synchronous, because concurrent rendering is
256
+ // only available in versions of React that also have a built-in
257
+ // useSyncExternalStore API. And we only use this shim when the built-in API
258
+ // does not exist.
259
+ //
260
+ // Do not assume that the clever hacks used by this hook also work in general.
261
+ // The point of this shim is to replace the need for hacks by other libraries.
262
+
263
+ function useSyncExternalStore(subscribe, getSnapshot, // Note: The shim does not use getServerSnapshot, because pre-18 versions of
264
+ // React do not expose a way to check if we're hydrating. So users of the shim
265
+ // will need to track that themselves and return the correct value
266
+ // from `getSnapshot`.
267
+ getServerSnapshot) {
268
+ {
269
+ if (!didWarnOld18Alpha) {
270
+ if (React$1.startTransition !== undefined) {
271
+ didWarnOld18Alpha = true;
272
+
273
+ 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.');
274
+ }
275
+ }
276
+ } // Read the current snapshot from the store on every render. Again, this
277
+ // breaks the rules of React, and only works here because of specific
278
+ // implementation details, most importantly that updates are
279
+ // always synchronous.
280
+
281
+
282
+ var value = getSnapshot();
283
+
284
+ {
285
+ if (!didWarnUncachedGetSnapshot) {
286
+ var cachedValue = getSnapshot();
287
+
288
+ if (!objectIs(value, cachedValue)) {
289
+ error('The result of getSnapshot should be cached to avoid an infinite loop');
290
+
291
+ didWarnUncachedGetSnapshot = true;
292
+ }
293
+ }
294
+ } // Because updates are synchronous, we don't queue them. Instead we force a
295
+ // re-render whenever the subscribed state changes by updating an some
296
+ // arbitrary useState hook. Then, during render, we call getSnapshot to read
297
+ // the current value.
298
+ //
299
+ // Because we don't actually use the state returned by the useState hook, we
300
+ // can save a bit of memory by storing other stuff in that slot.
301
+ //
302
+ // To implement the early bailout, we need to track some things on a mutable
303
+ // object. Usually, we would put that in a useRef hook, but we can stash it in
304
+ // our useState hook instead.
305
+ //
306
+ // To force a re-render, we call forceUpdate({inst}). That works because the
307
+ // new object always fails an equality check.
308
+
309
+
310
+ var _useState = useState({
311
+ inst: {
312
+ value: value,
313
+ getSnapshot: getSnapshot
314
+ }
315
+ }),
316
+ inst = _useState[0].inst,
317
+ forceUpdate = _useState[1]; // Track the latest getSnapshot function with a ref. This needs to be updated
318
+ // in the layout phase so we can access it during the tearing check that
319
+ // happens on subscribe.
320
+
321
+
322
+ useLayoutEffect(function () {
323
+ inst.value = value;
324
+ inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the
325
+ // commit phase if there was an interleaved mutation. In concurrent mode
326
+ // this can happen all the time, but even in synchronous mode, an earlier
327
+ // effect may have mutated the store.
328
+
329
+ if (checkIfSnapshotChanged(inst)) {
330
+ // Force a re-render.
331
+ forceUpdate({
332
+ inst: inst
333
+ });
334
+ }
335
+ }, [subscribe, value, getSnapshot]);
336
+ useEffect(function () {
337
+ // Check for changes right before subscribing. Subsequent changes will be
338
+ // detected in the subscription handler.
339
+ if (checkIfSnapshotChanged(inst)) {
340
+ // Force a re-render.
341
+ forceUpdate({
342
+ inst: inst
343
+ });
344
+ }
345
+
346
+ var handleStoreChange = function () {
347
+ // TODO: Because there is no cross-renderer API for batching updates, it's
348
+ // up to the consumer of this library to wrap their subscription event
349
+ // with unstable_batchedUpdates. Should we try to detect when this isn't
350
+ // the case and print a warning in development?
351
+ // The store changed. Check if the snapshot changed since the last time we
352
+ // read from the store.
353
+ if (checkIfSnapshotChanged(inst)) {
354
+ // Force a re-render.
355
+ forceUpdate({
356
+ inst: inst
357
+ });
358
+ }
359
+ }; // Subscribe to the store and return a clean-up function.
360
+
361
+
362
+ return subscribe(handleStoreChange);
363
+ }, [subscribe]);
364
+ useDebugValue(value);
365
+ return value;
366
+ }
367
+
368
+ function checkIfSnapshotChanged(inst) {
369
+ var latestGetSnapshot = inst.getSnapshot;
370
+ var prevValue = inst.value;
371
+
372
+ try {
373
+ var nextValue = latestGetSnapshot();
374
+ return !objectIs(prevValue, nextValue);
375
+ } catch (error) {
376
+ return true;
377
+ }
378
+ }
379
+
380
+ function useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {
381
+ // Note: The shim does not use getServerSnapshot, because pre-18 versions of
382
+ // React do not expose a way to check if we're hydrating. So users of the shim
383
+ // will need to track that themselves and return the correct value
384
+ // from `getSnapshot`.
385
+ return getSnapshot();
386
+ }
387
+
388
+ var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');
389
+
390
+ var isServerEnvironment = !canUseDOM;
391
+
392
+ var shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore;
393
+ var useSyncExternalStore$2 = React$1.useSyncExternalStore !== undefined ? React$1.useSyncExternalStore : shim;
394
+
395
+ useSyncExternalStoreShim_development.useSyncExternalStore = useSyncExternalStore$2;
396
+ /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
397
+ if (
398
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
399
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===
400
+ 'function'
401
+ ) {
402
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
403
+ }
404
+
405
+ })();
406
+ }
407
+ return useSyncExternalStoreShim_development;
408
+ }
409
+
410
+ var hasRequiredShim;
411
+
412
+ function requireShim () {
413
+ if (hasRequiredShim) return shim.exports;
414
+ hasRequiredShim = 1;
415
+
416
+ if (process.env.NODE_ENV === 'production') {
417
+ shim.exports = requireUseSyncExternalStoreShim_production_min();
418
+ } else {
419
+ shim.exports = requireUseSyncExternalStoreShim_development();
420
+ }
421
+ return shim.exports;
422
+ }
423
+
424
+ /**
425
+ * @license React
426
+ * use-sync-external-store-shim/with-selector.production.min.js
427
+ *
428
+ * Copyright (c) Facebook, Inc. and its affiliates.
429
+ *
430
+ * This source code is licensed under the MIT license found in the
431
+ * LICENSE file in the root directory of this source tree.
432
+ */
433
+
434
+ var hasRequiredWithSelector_production_min;
435
+
436
+ function requireWithSelector_production_min () {
437
+ if (hasRequiredWithSelector_production_min) return withSelector_production_min;
438
+ hasRequiredWithSelector_production_min = 1;
439
+ var h=React,n=requireShim();function p(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var q="function"===typeof Object.is?Object.is:p,r=n.useSyncExternalStore,t=h.useRef,u=h.useEffect,v=h.useMemo,w=h.useDebugValue;
440
+ 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]);
441
+ u(function(){f.hasValue=!0;f.value=d;},[d]);w(d);return d};
442
+ return withSelector_production_min;
443
+ }
444
+
445
+ var withSelector_development = {};
446
+
447
+ /**
448
+ * @license React
449
+ * use-sync-external-store-shim/with-selector.development.js
450
+ *
451
+ * Copyright (c) Facebook, Inc. and its affiliates.
452
+ *
453
+ * This source code is licensed under the MIT license found in the
454
+ * LICENSE file in the root directory of this source tree.
455
+ */
456
+
457
+ var hasRequiredWithSelector_development;
458
+
459
+ function requireWithSelector_development () {
460
+ if (hasRequiredWithSelector_development) return withSelector_development;
461
+ hasRequiredWithSelector_development = 1;
462
+
463
+ if (process.env.NODE_ENV !== "production") {
464
+ (function() {
465
+
466
+ /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
467
+ if (
468
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
469
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===
470
+ 'function'
471
+ ) {
472
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
473
+ }
474
+ var React$1 = React;
475
+ var shim = requireShim();
476
+
477
+ /**
478
+ * inlined Object.is polyfill to avoid requiring consumers ship their own
479
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
480
+ */
481
+ function is(x, y) {
482
+ return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
483
+ ;
484
+ }
485
+
486
+ var objectIs = typeof Object.is === 'function' ? Object.is : is;
487
+
488
+ var useSyncExternalStore = shim.useSyncExternalStore;
489
+
490
+ // for CommonJS interop.
491
+
492
+ var useRef = React$1.useRef,
493
+ useEffect = React$1.useEffect,
494
+ useMemo = React$1.useMemo,
495
+ useDebugValue = React$1.useDebugValue; // Same as useSyncExternalStore, but supports selector and isEqual arguments.
496
+
497
+ function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {
498
+ // Use this to track the rendered snapshot.
499
+ var instRef = useRef(null);
500
+ var inst;
501
+
502
+ if (instRef.current === null) {
503
+ inst = {
504
+ hasValue: false,
505
+ value: null
506
+ };
507
+ instRef.current = inst;
508
+ } else {
509
+ inst = instRef.current;
510
+ }
511
+
512
+ var _useMemo = useMemo(function () {
513
+ // Track the memoized state using closure variables that are local to this
514
+ // memoized instance of a getSnapshot function. Intentionally not using a
515
+ // useRef hook, because that state would be shared across all concurrent
516
+ // copies of the hook/component.
517
+ var hasMemo = false;
518
+ var memoizedSnapshot;
519
+ var memoizedSelection;
520
+
521
+ var memoizedSelector = function (nextSnapshot) {
522
+ if (!hasMemo) {
523
+ // The first time the hook is called, there is no memoized result.
524
+ hasMemo = true;
525
+ memoizedSnapshot = nextSnapshot;
526
+
527
+ var _nextSelection = selector(nextSnapshot);
528
+
529
+ if (isEqual !== undefined) {
530
+ // Even if the selector has changed, the currently rendered selection
531
+ // may be equal to the new selection. We should attempt to reuse the
532
+ // current value if possible, to preserve downstream memoizations.
533
+ if (inst.hasValue) {
534
+ var currentSelection = inst.value;
535
+
536
+ if (isEqual(currentSelection, _nextSelection)) {
537
+ memoizedSelection = currentSelection;
538
+ return currentSelection;
539
+ }
540
+ }
541
+ }
542
+
543
+ memoizedSelection = _nextSelection;
544
+ return _nextSelection;
545
+ } // We may be able to reuse the previous invocation's result.
546
+
547
+
548
+ // We may be able to reuse the previous invocation's result.
549
+ var prevSnapshot = memoizedSnapshot;
550
+ var prevSelection = memoizedSelection;
551
+
552
+ if (objectIs(prevSnapshot, nextSnapshot)) {
553
+ // The snapshot is the same as last time. Reuse the previous selection.
554
+ return prevSelection;
555
+ } // The snapshot has changed, so we need to compute a new selection.
556
+
557
+
558
+ // The snapshot has changed, so we need to compute a new selection.
559
+ var nextSelection = selector(nextSnapshot); // If a custom isEqual function is provided, use that to check if the data
560
+ // has changed. If it hasn't, return the previous selection. That signals
561
+ // to React that the selections are conceptually equal, and we can bail
562
+ // out of rendering.
563
+
564
+ // If a custom isEqual function is provided, use that to check if the data
565
+ // has changed. If it hasn't, return the previous selection. That signals
566
+ // to React that the selections are conceptually equal, and we can bail
567
+ // out of rendering.
568
+ if (isEqual !== undefined && isEqual(prevSelection, nextSelection)) {
569
+ return prevSelection;
570
+ }
571
+
572
+ memoizedSnapshot = nextSnapshot;
573
+ memoizedSelection = nextSelection;
574
+ return nextSelection;
575
+ }; // Assigning this to a constant so that Flow knows it can't change.
576
+
577
+
578
+ // Assigning this to a constant so that Flow knows it can't change.
579
+ var maybeGetServerSnapshot = getServerSnapshot === undefined ? null : getServerSnapshot;
580
+
581
+ var getSnapshotWithSelector = function () {
582
+ return memoizedSelector(getSnapshot());
583
+ };
584
+
585
+ var getServerSnapshotWithSelector = maybeGetServerSnapshot === null ? undefined : function () {
586
+ return memoizedSelector(maybeGetServerSnapshot());
587
+ };
588
+ return [getSnapshotWithSelector, getServerSnapshotWithSelector];
589
+ }, [getSnapshot, getServerSnapshot, selector, isEqual]),
590
+ getSelection = _useMemo[0],
591
+ getServerSelection = _useMemo[1];
592
+
593
+ var value = useSyncExternalStore(subscribe, getSelection, getServerSelection);
594
+ useEffect(function () {
595
+ inst.hasValue = true;
596
+ inst.value = value;
597
+ }, [value]);
598
+ useDebugValue(value);
599
+ return value;
600
+ }
601
+
602
+ withSelector_development.useSyncExternalStoreWithSelector = useSyncExternalStoreWithSelector;
603
+ /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
604
+ if (
605
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
606
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===
607
+ 'function'
608
+ ) {
609
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
610
+ }
611
+
612
+ })();
613
+ }
614
+ return withSelector_development;
615
+ }
616
+
617
+ if (process.env.NODE_ENV === 'production') {
618
+ withSelector.exports = requireWithSelector_production_min();
619
+ } else {
620
+ withSelector.exports = requireWithSelector_development();
621
+ }
622
+
623
+ var withSelectorExports = withSelector.exports;
624
+
136
625
  /**
137
- * This hook allows you to create an editor instance.
138
- * @param options The editor options
139
- * @param deps The dependencies to watch for changes
140
- * @returns The editor instance
141
- * @example const editor = useEditor({ extensions: [...] })
626
+ * To synchronize the editor instance with the component state,
627
+ * we need to create a separate instance that is not affected by the component re-renders.
142
628
  */
143
- const useEditor = (options = {}, deps = []) => {
144
- const editorRef = useRef(null);
145
- const [, forceUpdate] = useState({});
629
+ function makeEditorStateInstance(initialEditor) {
630
+ let transactionNumber = 0;
631
+ let lastTransactionNumber = 0;
632
+ let lastSnapshot = { editor: initialEditor, transactionNumber: 0 };
633
+ let editor = initialEditor;
634
+ const subscribers = new Set();
635
+ const editorInstance = {
636
+ /**
637
+ * Get the current editor instance.
638
+ */
639
+ getSnapshot() {
640
+ if (transactionNumber === lastTransactionNumber) {
641
+ return lastSnapshot;
642
+ }
643
+ lastTransactionNumber = transactionNumber;
644
+ lastSnapshot = { editor, transactionNumber };
645
+ return lastSnapshot;
646
+ },
647
+ /**
648
+ * Always disable the editor on the server-side.
649
+ */
650
+ getServerSnapshot() {
651
+ return { editor: null, transactionNumber: 0 };
652
+ },
653
+ /**
654
+ * Subscribe to the editor instance's changes.
655
+ */
656
+ subscribe(callback) {
657
+ subscribers.add(callback);
658
+ return () => {
659
+ subscribers.delete(callback);
660
+ };
661
+ },
662
+ /**
663
+ * Watch the editor instance for changes.
664
+ */
665
+ watch(nextEditor) {
666
+ editor = nextEditor;
667
+ if (editor) {
668
+ /**
669
+ * This will force a re-render when the editor state changes.
670
+ * This is to support things like `editor.can().toggleBold()` in components that `useEditor`.
671
+ * This could be more efficient, but it's a good trade-off for now.
672
+ */
673
+ const fn = () => {
674
+ transactionNumber += 1;
675
+ subscribers.forEach(callback => callback());
676
+ };
677
+ const currentEditor = editor;
678
+ currentEditor.on('transaction', fn);
679
+ return () => {
680
+ currentEditor.off('transaction', fn);
681
+ };
682
+ }
683
+ },
684
+ };
685
+ return editorInstance;
686
+ }
687
+ function useEditorState(options) {
688
+ const [editorInstance] = useState(() => makeEditorStateInstance(options.editor));
689
+ // Using the `useSyncExternalStore` hook to sync the editor instance with the component state
690
+ const selectedState = withSelectorExports.useSyncExternalStoreWithSelector(editorInstance.subscribe, editorInstance.getSnapshot, editorInstance.getServerSnapshot, options.selector, options.equalityFn);
691
+ useEffect(() => {
692
+ return editorInstance.watch(options.editor);
693
+ }, [options.editor]);
694
+ useDebugValue(selectedState);
695
+ return selectedState;
696
+ }
697
+
698
+ const isDev = process.env.NODE_ENV !== 'production';
699
+ const isSSR = typeof window === 'undefined';
700
+ const isNext = isSSR || Boolean(typeof window !== 'undefined' && window.next);
701
+ function useEditor(options = {}, deps = []) {
702
+ const isMounted = useRef(false);
703
+ const [editor, setEditor] = useState(() => {
704
+ if (options.immediatelyRender === undefined) {
705
+ if (isSSR || isNext) {
706
+ // TODO in the next major release, we should throw an error here
707
+ if (isDev) {
708
+ /**
709
+ * Throw an error in development, to make sure the developer is aware that tiptap cannot be SSR'd
710
+ * and that they need to set `immediatelyRender` to `false` to avoid hydration mismatches.
711
+ */
712
+ console.warn('Tiptap Error: SSR has been detected, please set `immediatelyRender` explicitly to `false` to avoid hydration mismatches.');
713
+ }
714
+ // Best faith effort in production, run the code in the legacy mode to avoid hydration mismatches and errors in production
715
+ return null;
716
+ }
717
+ // Default to immediately rendering when client-side rendering
718
+ return new Editor(options);
719
+ }
720
+ if (options.immediatelyRender && isSSR && isDev) {
721
+ // Warn in development, to make sure the developer is aware that tiptap cannot be SSR'd, set `immediatelyRender` to `false` to avoid hydration mismatches.
722
+ 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.');
723
+ }
724
+ if (options.immediatelyRender) {
725
+ return new Editor(options);
726
+ }
727
+ return null;
728
+ });
729
+ useDebugValue(editor);
730
+ // This effect will handle creating/updating the editor instance
731
+ useEffect(() => {
732
+ let editorInstance = editor;
733
+ if (!editorInstance) {
734
+ editorInstance = new Editor(options);
735
+ // instantiate the editor if it doesn't exist
736
+ // for ssr, this is the first time the editor is created
737
+ setEditor(editorInstance);
738
+ }
739
+ else {
740
+ // if the editor does exist, update the editor options accordingly
741
+ editorInstance.setOptions(options);
742
+ }
743
+ }, deps);
146
744
  const { onBeforeCreate, onBlur, onCreate, onDestroy, onFocus, onSelectionUpdate, onTransaction, onUpdate, onContentError, } = options;
147
745
  const onBeforeCreateRef = useRef(onBeforeCreate);
148
746
  const onBlurRef = useRef(onBlur);
@@ -156,82 +754,122 @@ const useEditor = (options = {}, deps = []) => {
156
754
  // This effect will handle updating the editor instance
157
755
  // when the event handlers change.
158
756
  useEffect(() => {
159
- if (!editorRef.current) {
757
+ if (!editor) {
160
758
  return;
161
759
  }
162
760
  if (onBeforeCreate) {
163
- editorRef.current.off('beforeCreate', onBeforeCreateRef.current);
164
- editorRef.current.on('beforeCreate', onBeforeCreate);
761
+ editor.off('beforeCreate', onBeforeCreateRef.current);
762
+ editor.on('beforeCreate', onBeforeCreate);
165
763
  onBeforeCreateRef.current = onBeforeCreate;
166
764
  }
167
765
  if (onBlur) {
168
- editorRef.current.off('blur', onBlurRef.current);
169
- editorRef.current.on('blur', onBlur);
766
+ editor.off('blur', onBlurRef.current);
767
+ editor.on('blur', onBlur);
170
768
  onBlurRef.current = onBlur;
171
769
  }
172
770
  if (onCreate) {
173
- editorRef.current.off('create', onCreateRef.current);
174
- editorRef.current.on('create', onCreate);
771
+ editor.off('create', onCreateRef.current);
772
+ editor.on('create', onCreate);
175
773
  onCreateRef.current = onCreate;
176
774
  }
177
775
  if (onDestroy) {
178
- editorRef.current.off('destroy', onDestroyRef.current);
179
- editorRef.current.on('destroy', onDestroy);
776
+ editor.off('destroy', onDestroyRef.current);
777
+ editor.on('destroy', onDestroy);
180
778
  onDestroyRef.current = onDestroy;
181
779
  }
182
780
  if (onFocus) {
183
- editorRef.current.off('focus', onFocusRef.current);
184
- editorRef.current.on('focus', onFocus);
781
+ editor.off('focus', onFocusRef.current);
782
+ editor.on('focus', onFocus);
185
783
  onFocusRef.current = onFocus;
186
784
  }
187
785
  if (onSelectionUpdate) {
188
- editorRef.current.off('selectionUpdate', onSelectionUpdateRef.current);
189
- editorRef.current.on('selectionUpdate', onSelectionUpdate);
786
+ editor.off('selectionUpdate', onSelectionUpdateRef.current);
787
+ editor.on('selectionUpdate', onSelectionUpdate);
190
788
  onSelectionUpdateRef.current = onSelectionUpdate;
191
789
  }
192
790
  if (onTransaction) {
193
- editorRef.current.off('transaction', onTransactionRef.current);
194
- editorRef.current.on('transaction', onTransaction);
791
+ editor.off('transaction', onTransactionRef.current);
792
+ editor.on('transaction', onTransaction);
195
793
  onTransactionRef.current = onTransaction;
196
794
  }
197
795
  if (onUpdate) {
198
- editorRef.current.off('update', onUpdateRef.current);
199
- editorRef.current.on('update', onUpdate);
796
+ editor.off('update', onUpdateRef.current);
797
+ editor.on('update', onUpdate);
200
798
  onUpdateRef.current = onUpdate;
201
799
  }
202
800
  if (onContentError) {
203
- editorRef.current.off('contentError', onContentErrorRef.current);
204
- editorRef.current.on('contentError', onContentError);
801
+ editor.off('contentError', onContentErrorRef.current);
802
+ editor.on('contentError', onContentError);
205
803
  onContentErrorRef.current = onContentError;
206
804
  }
207
- }, [onBeforeCreate, onBlur, onCreate, onDestroy, onFocus, onSelectionUpdate, onTransaction, onUpdate, editorRef.current]);
805
+ }, [
806
+ onBeforeCreate,
807
+ onBlur,
808
+ onCreate,
809
+ onDestroy,
810
+ onFocus,
811
+ onSelectionUpdate,
812
+ onTransaction,
813
+ onUpdate,
814
+ onContentError,
815
+ editor,
816
+ ]);
817
+ /**
818
+ * Destroy the editor instance when the component completely unmounts
819
+ * As opposed to the cleanup function in the effect above, this will
820
+ * only be called when the component is removed from the DOM, since it has no deps.
821
+ * */
208
822
  useEffect(() => {
209
- let isMounted = true;
210
- const editor = new Editor(options);
211
- editorRef.current = editor;
212
- editorRef.current.on('transaction', () => {
213
- requestAnimationFrame(() => {
214
- requestAnimationFrame(() => {
215
- if (isMounted) {
216
- forceUpdate({});
823
+ isMounted.current = true;
824
+ return () => {
825
+ isMounted.current = false;
826
+ if (editor) {
827
+ // We need to destroy the editor asynchronously to avoid memory leaks
828
+ // because the editor instance is still being used in the component.
829
+ setTimeout(() => {
830
+ // re-use the editor instance if it hasn't been destroyed yet
831
+ // and the component is still mounted
832
+ // otherwise, asynchronously destroy the editor instance
833
+ if (!isMounted.current && !editor.isDestroyed) {
834
+ editor.destroy();
217
835
  }
218
836
  });
219
- });
220
- });
221
- return () => {
222
- isMounted = false;
223
- editor.destroy();
837
+ }
224
838
  };
225
- }, deps);
226
- return editorRef.current;
227
- };
839
+ }, []);
840
+ // The default behavior is to re-render on each transaction
841
+ // This is legacy behavior that will be removed in future versions
842
+ useEditorState({
843
+ editor,
844
+ selector: ({ transactionNumber }) => {
845
+ if (options.shouldRerenderOnTransaction === false) {
846
+ // This will prevent the editor from re-rendering on each transaction
847
+ return null;
848
+ }
849
+ // This will avoid re-rendering on the first transaction when `immediatelyRender` is set to `true`
850
+ if (options.immediatelyRender && transactionNumber === 0) {
851
+ return 0;
852
+ }
853
+ return transactionNumber + 1;
854
+ },
855
+ });
856
+ return editor;
857
+ }
228
858
 
229
859
  const EditorContext = createContext({
230
860
  editor: null,
231
861
  });
232
862
  const EditorConsumer = EditorContext.Consumer;
863
+ /**
864
+ * A hook to get the current editor instance.
865
+ */
233
866
  const useCurrentEditor = () => useContext(EditorContext);
234
- const EditorProvider = ({ children, slotAfter, slotBefore, ...editorOptions }) => {
867
+ /**
868
+ * This is the provider component for the editor.
869
+ * It allows the editor to be accessible across the entire component tree
870
+ * with `useCurrentEditor`.
871
+ */
872
+ function EditorProvider({ children, slotAfter, slotBefore, ...editorOptions }) {
235
873
  const editor = useEditor(editorOptions);
236
874
  if (!editor) {
237
875
  return null;
@@ -241,7 +879,7 @@ const EditorProvider = ({ children, slotAfter, slotBefore, ...editorOptions }) =
241
879
  React.createElement(EditorConsumer, null, ({ editor: currentEditor }) => (React.createElement(EditorContent, { editor: currentEditor }))),
242
880
  children,
243
881
  slotAfter));
244
- };
882
+ }
245
883
 
246
884
  const BubbleMenu = (props) => {
247
885
  const [element, setElement] = useState(null);
@@ -554,5 +1192,5 @@ function ReactNodeViewRenderer(component, options) {
554
1192
  };
555
1193
  }
556
1194
 
557
- export { BubbleMenu, Editor, EditorConsumer, EditorContent, EditorContext, EditorProvider, FloatingMenu, NodeViewContent, NodeViewWrapper, PureEditorContent, ReactNodeViewContext, ReactNodeViewRenderer, ReactRenderer, useCurrentEditor, useEditor, useReactNodeView };
1195
+ export { BubbleMenu, Editor, EditorConsumer, EditorContent, EditorContext, EditorProvider, FloatingMenu, NodeViewContent, NodeViewWrapper, PureEditorContent, ReactNodeViewContext, ReactNodeViewRenderer, ReactRenderer, useCurrentEditor, useEditor, useEditorState, useReactNodeView };
558
1196
  //# sourceMappingURL=index.js.map