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