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