@tiptap/react
Advanced tools
Comparing version 2.5.0-pre.13 to 2.5.0-pre.14
import { BubbleMenuPlugin } from '@tiptap/extension-bubble-menu'; | ||
import React, { forwardRef, useRef, useState, useEffect, createContext, useContext } from 'react'; | ||
import React, { forwardRef, useState, useEffect, useDebugValue, useRef, createContext, useContext } from 'react'; | ||
import ReactDOM, { flushSync } from 'react-dom'; | ||
@@ -136,12 +136,609 @@ import { Editor as Editor$1, NodeView } from '@tiptap/core'; | ||
var withSelector = {exports: {}}; | ||
var withSelector_production_min = {}; | ||
var shim = {exports: {}}; | ||
var useSyncExternalStoreShim_production_min = {}; | ||
/** | ||
* This hook allows you to create an editor instance. | ||
* @param options The editor options | ||
* @param deps The dependencies to watch for changes | ||
* @returns The editor instance | ||
* @example const editor = useEditor({ extensions: [...] }) | ||
* @license React | ||
* use-sync-external-store-shim.production.min.js | ||
* | ||
* Copyright (c) Facebook, Inc. and its affiliates. | ||
* | ||
* This source code is licensed under the MIT license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
*/ | ||
const useEditor = (options = {}, deps = []) => { | ||
const editorRef = useRef(null); | ||
const [, forceUpdate] = useState({}); | ||
var hasRequiredUseSyncExternalStoreShim_production_min; | ||
function requireUseSyncExternalStoreShim_production_min () { | ||
if (hasRequiredUseSyncExternalStoreShim_production_min) return useSyncExternalStoreShim_production_min; | ||
hasRequiredUseSyncExternalStoreShim_production_min = 1; | ||
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} | ||
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; | ||
return useSyncExternalStoreShim_production_min; | ||
} | ||
var useSyncExternalStoreShim_development = {}; | ||
/** | ||
* @license React | ||
* use-sync-external-store-shim.development.js | ||
* | ||
* Copyright (c) Facebook, Inc. and its affiliates. | ||
* | ||
* This source code is licensed under the MIT license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
*/ | ||
var hasRequiredUseSyncExternalStoreShim_development; | ||
function requireUseSyncExternalStoreShim_development () { | ||
if (hasRequiredUseSyncExternalStoreShim_development) return useSyncExternalStoreShim_development; | ||
hasRequiredUseSyncExternalStoreShim_development = 1; | ||
if (process.env.NODE_ENV !== "production") { | ||
(function() { | ||
/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ | ||
if ( | ||
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && | ||
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === | ||
'function' | ||
) { | ||
__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); | ||
} | ||
var React$1 = React; | ||
var ReactSharedInternals = React$1.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; | ||
function error(format) { | ||
{ | ||
{ | ||
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { | ||
args[_key2 - 1] = arguments[_key2]; | ||
} | ||
printWarning('error', format, args); | ||
} | ||
} | ||
} | ||
function printWarning(level, format, args) { | ||
// When changing this logic, you might want to also | ||
// update consoleWithStackDev.www.js as well. | ||
{ | ||
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; | ||
var stack = ReactDebugCurrentFrame.getStackAddendum(); | ||
if (stack !== '') { | ||
format += '%s'; | ||
args = args.concat([stack]); | ||
} // eslint-disable-next-line react-internal/safe-string-coercion | ||
var argsWithFormat = args.map(function (item) { | ||
return String(item); | ||
}); // Careful: RN currently depends on this prefix | ||
argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it | ||
// breaks IE9: https://github.com/facebook/react/issues/13610 | ||
// eslint-disable-next-line react-internal/no-production-logging | ||
Function.prototype.apply.call(console[level], console, argsWithFormat); | ||
} | ||
} | ||
/** | ||
* inlined Object.is polyfill to avoid requiring consumers ship their own | ||
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is | ||
*/ | ||
function is(x, y) { | ||
return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare | ||
; | ||
} | ||
var objectIs = typeof Object.is === 'function' ? Object.is : is; | ||
// dispatch for CommonJS interop named imports. | ||
var useState = React$1.useState, | ||
useEffect = React$1.useEffect, | ||
useLayoutEffect = React$1.useLayoutEffect, | ||
useDebugValue = React$1.useDebugValue; | ||
var didWarnOld18Alpha = false; | ||
var didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works | ||
// because of a very particular set of implementation details and assumptions | ||
// -- change any one of them and it will break. The most important assumption | ||
// is that updates are always synchronous, because concurrent rendering is | ||
// only available in versions of React that also have a built-in | ||
// useSyncExternalStore API. And we only use this shim when the built-in API | ||
// does not exist. | ||
// | ||
// Do not assume that the clever hacks used by this hook also work in general. | ||
// The point of this shim is to replace the need for hacks by other libraries. | ||
function useSyncExternalStore(subscribe, getSnapshot, // Note: The shim does not use getServerSnapshot, because pre-18 versions of | ||
// React do not expose a way to check if we're hydrating. So users of the shim | ||
// will need to track that themselves and return the correct value | ||
// from `getSnapshot`. | ||
getServerSnapshot) { | ||
{ | ||
if (!didWarnOld18Alpha) { | ||
if (React$1.startTransition !== undefined) { | ||
didWarnOld18Alpha = true; | ||
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.'); | ||
} | ||
} | ||
} // Read the current snapshot from the store on every render. Again, this | ||
// breaks the rules of React, and only works here because of specific | ||
// implementation details, most importantly that updates are | ||
// always synchronous. | ||
var value = getSnapshot(); | ||
{ | ||
if (!didWarnUncachedGetSnapshot) { | ||
var cachedValue = getSnapshot(); | ||
if (!objectIs(value, cachedValue)) { | ||
error('The result of getSnapshot should be cached to avoid an infinite loop'); | ||
didWarnUncachedGetSnapshot = true; | ||
} | ||
} | ||
} // Because updates are synchronous, we don't queue them. Instead we force a | ||
// re-render whenever the subscribed state changes by updating an some | ||
// arbitrary useState hook. Then, during render, we call getSnapshot to read | ||
// the current value. | ||
// | ||
// Because we don't actually use the state returned by the useState hook, we | ||
// can save a bit of memory by storing other stuff in that slot. | ||
// | ||
// To implement the early bailout, we need to track some things on a mutable | ||
// object. Usually, we would put that in a useRef hook, but we can stash it in | ||
// our useState hook instead. | ||
// | ||
// To force a re-render, we call forceUpdate({inst}). That works because the | ||
// new object always fails an equality check. | ||
var _useState = useState({ | ||
inst: { | ||
value: value, | ||
getSnapshot: getSnapshot | ||
} | ||
}), | ||
inst = _useState[0].inst, | ||
forceUpdate = _useState[1]; // Track the latest getSnapshot function with a ref. This needs to be updated | ||
// in the layout phase so we can access it during the tearing check that | ||
// happens on subscribe. | ||
useLayoutEffect(function () { | ||
inst.value = value; | ||
inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the | ||
// commit phase if there was an interleaved mutation. In concurrent mode | ||
// this can happen all the time, but even in synchronous mode, an earlier | ||
// effect may have mutated the store. | ||
if (checkIfSnapshotChanged(inst)) { | ||
// Force a re-render. | ||
forceUpdate({ | ||
inst: inst | ||
}); | ||
} | ||
}, [subscribe, value, getSnapshot]); | ||
useEffect(function () { | ||
// Check for changes right before subscribing. Subsequent changes will be | ||
// detected in the subscription handler. | ||
if (checkIfSnapshotChanged(inst)) { | ||
// Force a re-render. | ||
forceUpdate({ | ||
inst: inst | ||
}); | ||
} | ||
var handleStoreChange = function () { | ||
// TODO: Because there is no cross-renderer API for batching updates, it's | ||
// up to the consumer of this library to wrap their subscription event | ||
// with unstable_batchedUpdates. Should we try to detect when this isn't | ||
// the case and print a warning in development? | ||
// The store changed. Check if the snapshot changed since the last time we | ||
// read from the store. | ||
if (checkIfSnapshotChanged(inst)) { | ||
// Force a re-render. | ||
forceUpdate({ | ||
inst: inst | ||
}); | ||
} | ||
}; // Subscribe to the store and return a clean-up function. | ||
return subscribe(handleStoreChange); | ||
}, [subscribe]); | ||
useDebugValue(value); | ||
return value; | ||
} | ||
function checkIfSnapshotChanged(inst) { | ||
var latestGetSnapshot = inst.getSnapshot; | ||
var prevValue = inst.value; | ||
try { | ||
var nextValue = latestGetSnapshot(); | ||
return !objectIs(prevValue, nextValue); | ||
} catch (error) { | ||
return true; | ||
} | ||
} | ||
function useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) { | ||
// Note: The shim does not use getServerSnapshot, because pre-18 versions of | ||
// React do not expose a way to check if we're hydrating. So users of the shim | ||
// will need to track that themselves and return the correct value | ||
// from `getSnapshot`. | ||
return getSnapshot(); | ||
} | ||
var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined'); | ||
var isServerEnvironment = !canUseDOM; | ||
var shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore; | ||
var useSyncExternalStore$2 = React$1.useSyncExternalStore !== undefined ? React$1.useSyncExternalStore : shim; | ||
useSyncExternalStoreShim_development.useSyncExternalStore = useSyncExternalStore$2; | ||
/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ | ||
if ( | ||
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && | ||
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === | ||
'function' | ||
) { | ||
__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); | ||
} | ||
})(); | ||
} | ||
return useSyncExternalStoreShim_development; | ||
} | ||
var hasRequiredShim; | ||
function requireShim () { | ||
if (hasRequiredShim) return shim.exports; | ||
hasRequiredShim = 1; | ||
if (process.env.NODE_ENV === 'production') { | ||
shim.exports = requireUseSyncExternalStoreShim_production_min(); | ||
} else { | ||
shim.exports = requireUseSyncExternalStoreShim_development(); | ||
} | ||
return shim.exports; | ||
} | ||
/** | ||
* @license React | ||
* use-sync-external-store-shim/with-selector.production.min.js | ||
* | ||
* Copyright (c) Facebook, Inc. and its affiliates. | ||
* | ||
* This source code is licensed under the MIT license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
*/ | ||
var hasRequiredWithSelector_production_min; | ||
function requireWithSelector_production_min () { | ||
if (hasRequiredWithSelector_production_min) return withSelector_production_min; | ||
hasRequiredWithSelector_production_min = 1; | ||
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; | ||
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]); | ||
u(function(){f.hasValue=!0;f.value=d;},[d]);w(d);return d}; | ||
return withSelector_production_min; | ||
} | ||
var withSelector_development = {}; | ||
/** | ||
* @license React | ||
* use-sync-external-store-shim/with-selector.development.js | ||
* | ||
* Copyright (c) Facebook, Inc. and its affiliates. | ||
* | ||
* This source code is licensed under the MIT license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
*/ | ||
var hasRequiredWithSelector_development; | ||
function requireWithSelector_development () { | ||
if (hasRequiredWithSelector_development) return withSelector_development; | ||
hasRequiredWithSelector_development = 1; | ||
if (process.env.NODE_ENV !== "production") { | ||
(function() { | ||
/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ | ||
if ( | ||
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && | ||
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === | ||
'function' | ||
) { | ||
__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); | ||
} | ||
var React$1 = React; | ||
var shim = requireShim(); | ||
/** | ||
* inlined Object.is polyfill to avoid requiring consumers ship their own | ||
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is | ||
*/ | ||
function is(x, y) { | ||
return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare | ||
; | ||
} | ||
var objectIs = typeof Object.is === 'function' ? Object.is : is; | ||
var useSyncExternalStore = shim.useSyncExternalStore; | ||
// for CommonJS interop. | ||
var useRef = React$1.useRef, | ||
useEffect = React$1.useEffect, | ||
useMemo = React$1.useMemo, | ||
useDebugValue = React$1.useDebugValue; // Same as useSyncExternalStore, but supports selector and isEqual arguments. | ||
function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) { | ||
// Use this to track the rendered snapshot. | ||
var instRef = useRef(null); | ||
var inst; | ||
if (instRef.current === null) { | ||
inst = { | ||
hasValue: false, | ||
value: null | ||
}; | ||
instRef.current = inst; | ||
} else { | ||
inst = instRef.current; | ||
} | ||
var _useMemo = useMemo(function () { | ||
// Track the memoized state using closure variables that are local to this | ||
// memoized instance of a getSnapshot function. Intentionally not using a | ||
// useRef hook, because that state would be shared across all concurrent | ||
// copies of the hook/component. | ||
var hasMemo = false; | ||
var memoizedSnapshot; | ||
var memoizedSelection; | ||
var memoizedSelector = function (nextSnapshot) { | ||
if (!hasMemo) { | ||
// The first time the hook is called, there is no memoized result. | ||
hasMemo = true; | ||
memoizedSnapshot = nextSnapshot; | ||
var _nextSelection = selector(nextSnapshot); | ||
if (isEqual !== undefined) { | ||
// Even if the selector has changed, the currently rendered selection | ||
// may be equal to the new selection. We should attempt to reuse the | ||
// current value if possible, to preserve downstream memoizations. | ||
if (inst.hasValue) { | ||
var currentSelection = inst.value; | ||
if (isEqual(currentSelection, _nextSelection)) { | ||
memoizedSelection = currentSelection; | ||
return currentSelection; | ||
} | ||
} | ||
} | ||
memoizedSelection = _nextSelection; | ||
return _nextSelection; | ||
} // We may be able to reuse the previous invocation's result. | ||
// We may be able to reuse the previous invocation's result. | ||
var prevSnapshot = memoizedSnapshot; | ||
var prevSelection = memoizedSelection; | ||
if (objectIs(prevSnapshot, nextSnapshot)) { | ||
// The snapshot is the same as last time. Reuse the previous selection. | ||
return prevSelection; | ||
} // The snapshot has changed, so we need to compute a new selection. | ||
// The snapshot has changed, so we need to compute a new selection. | ||
var nextSelection = selector(nextSnapshot); // If a custom isEqual function is provided, use that to check if the data | ||
// has changed. If it hasn't, return the previous selection. That signals | ||
// to React that the selections are conceptually equal, and we can bail | ||
// out of rendering. | ||
// If a custom isEqual function is provided, use that to check if the data | ||
// has changed. If it hasn't, return the previous selection. That signals | ||
// to React that the selections are conceptually equal, and we can bail | ||
// out of rendering. | ||
if (isEqual !== undefined && isEqual(prevSelection, nextSelection)) { | ||
return prevSelection; | ||
} | ||
memoizedSnapshot = nextSnapshot; | ||
memoizedSelection = nextSelection; | ||
return nextSelection; | ||
}; // Assigning this to a constant so that Flow knows it can't change. | ||
// Assigning this to a constant so that Flow knows it can't change. | ||
var maybeGetServerSnapshot = getServerSnapshot === undefined ? null : getServerSnapshot; | ||
var getSnapshotWithSelector = function () { | ||
return memoizedSelector(getSnapshot()); | ||
}; | ||
var getServerSnapshotWithSelector = maybeGetServerSnapshot === null ? undefined : function () { | ||
return memoizedSelector(maybeGetServerSnapshot()); | ||
}; | ||
return [getSnapshotWithSelector, getServerSnapshotWithSelector]; | ||
}, [getSnapshot, getServerSnapshot, selector, isEqual]), | ||
getSelection = _useMemo[0], | ||
getServerSelection = _useMemo[1]; | ||
var value = useSyncExternalStore(subscribe, getSelection, getServerSelection); | ||
useEffect(function () { | ||
inst.hasValue = true; | ||
inst.value = value; | ||
}, [value]); | ||
useDebugValue(value); | ||
return value; | ||
} | ||
withSelector_development.useSyncExternalStoreWithSelector = useSyncExternalStoreWithSelector; | ||
/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ | ||
if ( | ||
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && | ||
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === | ||
'function' | ||
) { | ||
__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); | ||
} | ||
})(); | ||
} | ||
return withSelector_development; | ||
} | ||
if (process.env.NODE_ENV === 'production') { | ||
withSelector.exports = requireWithSelector_production_min(); | ||
} else { | ||
withSelector.exports = requireWithSelector_development(); | ||
} | ||
var withSelectorExports = withSelector.exports; | ||
/** | ||
* To synchronize the editor instance with the component state, | ||
* we need to create a separate instance that is not affected by the component re-renders. | ||
*/ | ||
function makeEditorStateInstance(initialEditor) { | ||
let transactionNumber = 0; | ||
let lastTransactionNumber = 0; | ||
let lastSnapshot = { editor: initialEditor, transactionNumber: 0 }; | ||
let editor = initialEditor; | ||
const subscribers = new Set(); | ||
const editorInstance = { | ||
/** | ||
* Get the current editor instance. | ||
*/ | ||
getSnapshot() { | ||
if (transactionNumber === lastTransactionNumber) { | ||
return lastSnapshot; | ||
} | ||
lastTransactionNumber = transactionNumber; | ||
lastSnapshot = { editor, transactionNumber }; | ||
return lastSnapshot; | ||
}, | ||
/** | ||
* Always disable the editor on the server-side. | ||
*/ | ||
getServerSnapshot() { | ||
return { editor: null, transactionNumber: 0 }; | ||
}, | ||
/** | ||
* Subscribe to the editor instance's changes. | ||
*/ | ||
subscribe(callback) { | ||
subscribers.add(callback); | ||
return () => { | ||
subscribers.delete(callback); | ||
}; | ||
}, | ||
/** | ||
* Watch the editor instance for changes. | ||
*/ | ||
watch(nextEditor) { | ||
editor = nextEditor; | ||
if (editor) { | ||
/** | ||
* This will force a re-render when the editor state changes. | ||
* This is to support things like `editor.can().toggleBold()` in components that `useEditor`. | ||
* This could be more efficient, but it's a good trade-off for now. | ||
*/ | ||
const fn = () => { | ||
transactionNumber += 1; | ||
subscribers.forEach(callback => callback()); | ||
}; | ||
const currentEditor = editor; | ||
currentEditor.on('transaction', fn); | ||
return () => { | ||
currentEditor.off('transaction', fn); | ||
}; | ||
} | ||
}, | ||
}; | ||
return editorInstance; | ||
} | ||
function useEditorState(options) { | ||
const [editorInstance] = useState(() => makeEditorStateInstance(options.editor)); | ||
// Using the `useSyncExternalStore` hook to sync the editor instance with the component state | ||
const selectedState = withSelectorExports.useSyncExternalStoreWithSelector(editorInstance.subscribe, editorInstance.getSnapshot, editorInstance.getServerSnapshot, options.selector, options.equalityFn); | ||
useEffect(() => { | ||
return editorInstance.watch(options.editor); | ||
}, [options.editor]); | ||
useDebugValue(selectedState); | ||
return selectedState; | ||
} | ||
const isDev = process.env.NODE_ENV !== 'production'; | ||
const isSSR = typeof window === 'undefined'; | ||
const isNext = isSSR || Boolean(typeof window !== 'undefined' && window.next); | ||
function useEditor(options = {}, deps = []) { | ||
const [editor, setEditor] = useState(() => { | ||
if (options.immediatelyRender === undefined) { | ||
if (isSSR || isNext) { | ||
// TODO in the next major release, we should throw an error here | ||
if (isDev) { | ||
/** | ||
* Throw an error in development, to make sure the developer is aware that tiptap cannot be SSR'd | ||
* and that they need to set `immediatelyRender` to `false` to avoid hydration mismatches. | ||
*/ | ||
console.warn('Tiptap Error: SSR has been detected, please set `immediatelyRender` explicitly to `false` to avoid hydration mismatches.'); | ||
} | ||
// Best faith effort in production, run the code in the legacy mode to avoid hydration mismatches and errors in production | ||
return null; | ||
} | ||
// Default to immediately rendering when client-side rendering | ||
return new Editor(options); | ||
} | ||
if (options.immediatelyRender && isSSR && isDev) { | ||
// Warn in development, to make sure the developer is aware that tiptap cannot be SSR'd, set `immediatelyRender` to `false` to avoid hydration mismatches. | ||
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.'); | ||
} | ||
if (options.immediatelyRender) { | ||
return new Editor(options); | ||
} | ||
return null; | ||
}); | ||
useDebugValue(editor); | ||
// This effect will handle creating/updating the editor instance | ||
useEffect(() => { | ||
let editorInstance = editor; | ||
if (!editorInstance) { | ||
editorInstance = new Editor(options); | ||
// instantiate the editor if it doesn't exist | ||
// for ssr, this is the first time the editor is created | ||
setEditor(editorInstance); | ||
} | ||
else { | ||
// if the editor does exist, update the editor options accordingly | ||
editorInstance.setOptions(options); | ||
} | ||
}, deps); | ||
const { onBeforeCreate, onBlur, onCreate, onDestroy, onFocus, onSelectionUpdate, onTransaction, onUpdate, onContentError, } = options; | ||
@@ -160,71 +757,94 @@ const onBeforeCreateRef = useRef(onBeforeCreate); | ||
useEffect(() => { | ||
if (!editorRef.current) { | ||
if (!editor) { | ||
return; | ||
} | ||
if (onBeforeCreate) { | ||
editorRef.current.off('beforeCreate', onBeforeCreateRef.current); | ||
editorRef.current.on('beforeCreate', onBeforeCreate); | ||
editor.off('beforeCreate', onBeforeCreateRef.current); | ||
editor.on('beforeCreate', onBeforeCreate); | ||
onBeforeCreateRef.current = onBeforeCreate; | ||
} | ||
if (onBlur) { | ||
editorRef.current.off('blur', onBlurRef.current); | ||
editorRef.current.on('blur', onBlur); | ||
editor.off('blur', onBlurRef.current); | ||
editor.on('blur', onBlur); | ||
onBlurRef.current = onBlur; | ||
} | ||
if (onCreate) { | ||
editorRef.current.off('create', onCreateRef.current); | ||
editorRef.current.on('create', onCreate); | ||
editor.off('create', onCreateRef.current); | ||
editor.on('create', onCreate); | ||
onCreateRef.current = onCreate; | ||
} | ||
if (onDestroy) { | ||
editorRef.current.off('destroy', onDestroyRef.current); | ||
editorRef.current.on('destroy', onDestroy); | ||
editor.off('destroy', onDestroyRef.current); | ||
editor.on('destroy', onDestroy); | ||
onDestroyRef.current = onDestroy; | ||
} | ||
if (onFocus) { | ||
editorRef.current.off('focus', onFocusRef.current); | ||
editorRef.current.on('focus', onFocus); | ||
editor.off('focus', onFocusRef.current); | ||
editor.on('focus', onFocus); | ||
onFocusRef.current = onFocus; | ||
} | ||
if (onSelectionUpdate) { | ||
editorRef.current.off('selectionUpdate', onSelectionUpdateRef.current); | ||
editorRef.current.on('selectionUpdate', onSelectionUpdate); | ||
editor.off('selectionUpdate', onSelectionUpdateRef.current); | ||
editor.on('selectionUpdate', onSelectionUpdate); | ||
onSelectionUpdateRef.current = onSelectionUpdate; | ||
} | ||
if (onTransaction) { | ||
editorRef.current.off('transaction', onTransactionRef.current); | ||
editorRef.current.on('transaction', onTransaction); | ||
editor.off('transaction', onTransactionRef.current); | ||
editor.on('transaction', onTransaction); | ||
onTransactionRef.current = onTransaction; | ||
} | ||
if (onUpdate) { | ||
editorRef.current.off('update', onUpdateRef.current); | ||
editorRef.current.on('update', onUpdate); | ||
editor.off('update', onUpdateRef.current); | ||
editor.on('update', onUpdate); | ||
onUpdateRef.current = onUpdate; | ||
} | ||
if (onContentError) { | ||
editorRef.current.off('contentError', onContentErrorRef.current); | ||
editorRef.current.on('contentError', onContentError); | ||
editor.off('contentError', onContentErrorRef.current); | ||
editor.on('contentError', onContentError); | ||
onContentErrorRef.current = onContentError; | ||
} | ||
}, [onBeforeCreate, onBlur, onCreate, onDestroy, onFocus, onSelectionUpdate, onTransaction, onUpdate, editorRef.current]); | ||
}, [ | ||
onBeforeCreate, | ||
onBlur, | ||
onCreate, | ||
onDestroy, | ||
onFocus, | ||
onSelectionUpdate, | ||
onTransaction, | ||
onUpdate, | ||
onContentError, | ||
editor, | ||
]); | ||
/** | ||
* Destroy the editor instance when the component completely unmounts | ||
* As opposed to the cleanup function in the effect above, this will | ||
* only be called when the component is removed from the DOM, since it has no deps. | ||
* */ | ||
useEffect(() => { | ||
let isMounted = true; | ||
const editor = new Editor(options); | ||
editorRef.current = editor; | ||
editorRef.current.on('transaction', () => { | ||
requestAnimationFrame(() => { | ||
requestAnimationFrame(() => { | ||
if (isMounted) { | ||
forceUpdate({}); | ||
} | ||
}); | ||
}); | ||
}); | ||
return () => { | ||
isMounted = false; | ||
editor.destroy(); | ||
if (editor) { | ||
// We need to destroy the editor asynchronously to avoid memory leaks | ||
// because the editor instance is still being used in the component. | ||
setTimeout(() => (editor.isDestroyed ? null : editor.destroy())); | ||
} | ||
}; | ||
}, deps); | ||
return editorRef.current; | ||
}; | ||
}, []); | ||
// The default behavior is to re-render on each transaction | ||
// This is legacy behavior that will be removed in future versions | ||
useEditorState({ | ||
editor, | ||
selector: ({ transactionNumber }) => { | ||
if (options.shouldRerenderOnTransaction === false) { | ||
// This will prevent the editor from re-rendering on each transaction | ||
return null; | ||
} | ||
// This will avoid re-rendering on the first transaction when `immediatelyRender` is set to `true` | ||
if (options.immediatelyRender && transactionNumber === 0) { | ||
return 0; | ||
} | ||
return transactionNumber + 1; | ||
}, | ||
}); | ||
return editor; | ||
} | ||
@@ -235,4 +855,12 @@ const EditorContext = createContext({ | ||
const EditorConsumer = EditorContext.Consumer; | ||
/** | ||
* A hook to get the current editor instance. | ||
*/ | ||
const useCurrentEditor = () => useContext(EditorContext); | ||
const EditorProvider = ({ children, slotAfter, slotBefore, ...editorOptions }) => { | ||
/** | ||
* This is the provider component for the editor. | ||
* It allows the editor to be accessible across the entire component tree | ||
* with `useCurrentEditor`. | ||
*/ | ||
function EditorProvider({ children, slotAfter, slotBefore, ...editorOptions }) { | ||
const editor = useEditor(editorOptions); | ||
@@ -247,3 +875,3 @@ if (!editor) { | ||
slotAfter)); | ||
}; | ||
} | ||
@@ -561,3 +1189,3 @@ const BubbleMenu = (props) => { | ||
export { BubbleMenu, Editor, EditorConsumer, EditorContent, EditorContext, EditorProvider, FloatingMenu, NodeViewContent, NodeViewWrapper, PureEditorContent, ReactNodeViewContext, ReactNodeViewRenderer, ReactRenderer, useCurrentEditor, useEditor, useReactNodeView }; | ||
export { BubbleMenu, Editor, EditorConsumer, EditorContent, EditorContext, EditorProvider, FloatingMenu, NodeViewContent, NodeViewWrapper, PureEditorContent, ReactNodeViewContext, ReactNodeViewRenderer, ReactRenderer, useCurrentEditor, useEditor, useEditorState, useReactNodeView }; | ||
//# sourceMappingURL=index.js.map |
@@ -135,12 +135,609 @@ (function (global, factory) { | ||
var withSelector = {exports: {}}; | ||
var withSelector_production_min = {}; | ||
var shim = {exports: {}}; | ||
var useSyncExternalStoreShim_production_min = {}; | ||
/** | ||
* This hook allows you to create an editor instance. | ||
* @param options The editor options | ||
* @param deps The dependencies to watch for changes | ||
* @returns The editor instance | ||
* @example const editor = useEditor({ extensions: [...] }) | ||
* @license React | ||
* use-sync-external-store-shim.production.min.js | ||
* | ||
* Copyright (c) Facebook, Inc. and its affiliates. | ||
* | ||
* This source code is licensed under the MIT license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
*/ | ||
const useEditor = (options = {}, deps = []) => { | ||
const editorRef = React.useRef(null); | ||
const [, forceUpdate] = React.useState({}); | ||
var hasRequiredUseSyncExternalStoreShim_production_min; | ||
function requireUseSyncExternalStoreShim_production_min () { | ||
if (hasRequiredUseSyncExternalStoreShim_production_min) return useSyncExternalStoreShim_production_min; | ||
hasRequiredUseSyncExternalStoreShim_production_min = 1; | ||
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} | ||
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; | ||
return useSyncExternalStoreShim_production_min; | ||
} | ||
var useSyncExternalStoreShim_development = {}; | ||
/** | ||
* @license React | ||
* use-sync-external-store-shim.development.js | ||
* | ||
* Copyright (c) Facebook, Inc. and its affiliates. | ||
* | ||
* This source code is licensed under the MIT license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
*/ | ||
var hasRequiredUseSyncExternalStoreShim_development; | ||
function requireUseSyncExternalStoreShim_development () { | ||
if (hasRequiredUseSyncExternalStoreShim_development) return useSyncExternalStoreShim_development; | ||
hasRequiredUseSyncExternalStoreShim_development = 1; | ||
if (process.env.NODE_ENV !== "production") { | ||
(function() { | ||
/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ | ||
if ( | ||
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && | ||
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === | ||
'function' | ||
) { | ||
__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); | ||
} | ||
var React$1 = React; | ||
var ReactSharedInternals = React$1.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; | ||
function error(format) { | ||
{ | ||
{ | ||
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { | ||
args[_key2 - 1] = arguments[_key2]; | ||
} | ||
printWarning('error', format, args); | ||
} | ||
} | ||
} | ||
function printWarning(level, format, args) { | ||
// When changing this logic, you might want to also | ||
// update consoleWithStackDev.www.js as well. | ||
{ | ||
var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; | ||
var stack = ReactDebugCurrentFrame.getStackAddendum(); | ||
if (stack !== '') { | ||
format += '%s'; | ||
args = args.concat([stack]); | ||
} // eslint-disable-next-line react-internal/safe-string-coercion | ||
var argsWithFormat = args.map(function (item) { | ||
return String(item); | ||
}); // Careful: RN currently depends on this prefix | ||
argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it | ||
// breaks IE9: https://github.com/facebook/react/issues/13610 | ||
// eslint-disable-next-line react-internal/no-production-logging | ||
Function.prototype.apply.call(console[level], console, argsWithFormat); | ||
} | ||
} | ||
/** | ||
* inlined Object.is polyfill to avoid requiring consumers ship their own | ||
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is | ||
*/ | ||
function is(x, y) { | ||
return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare | ||
; | ||
} | ||
var objectIs = typeof Object.is === 'function' ? Object.is : is; | ||
// dispatch for CommonJS interop named imports. | ||
var useState = React$1.useState, | ||
useEffect = React$1.useEffect, | ||
useLayoutEffect = React$1.useLayoutEffect, | ||
useDebugValue = React$1.useDebugValue; | ||
var didWarnOld18Alpha = false; | ||
var didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works | ||
// because of a very particular set of implementation details and assumptions | ||
// -- change any one of them and it will break. The most important assumption | ||
// is that updates are always synchronous, because concurrent rendering is | ||
// only available in versions of React that also have a built-in | ||
// useSyncExternalStore API. And we only use this shim when the built-in API | ||
// does not exist. | ||
// | ||
// Do not assume that the clever hacks used by this hook also work in general. | ||
// The point of this shim is to replace the need for hacks by other libraries. | ||
function useSyncExternalStore(subscribe, getSnapshot, // Note: The shim does not use getServerSnapshot, because pre-18 versions of | ||
// React do not expose a way to check if we're hydrating. So users of the shim | ||
// will need to track that themselves and return the correct value | ||
// from `getSnapshot`. | ||
getServerSnapshot) { | ||
{ | ||
if (!didWarnOld18Alpha) { | ||
if (React$1.startTransition !== undefined) { | ||
didWarnOld18Alpha = true; | ||
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.'); | ||
} | ||
} | ||
} // Read the current snapshot from the store on every render. Again, this | ||
// breaks the rules of React, and only works here because of specific | ||
// implementation details, most importantly that updates are | ||
// always synchronous. | ||
var value = getSnapshot(); | ||
{ | ||
if (!didWarnUncachedGetSnapshot) { | ||
var cachedValue = getSnapshot(); | ||
if (!objectIs(value, cachedValue)) { | ||
error('The result of getSnapshot should be cached to avoid an infinite loop'); | ||
didWarnUncachedGetSnapshot = true; | ||
} | ||
} | ||
} // Because updates are synchronous, we don't queue them. Instead we force a | ||
// re-render whenever the subscribed state changes by updating an some | ||
// arbitrary useState hook. Then, during render, we call getSnapshot to read | ||
// the current value. | ||
// | ||
// Because we don't actually use the state returned by the useState hook, we | ||
// can save a bit of memory by storing other stuff in that slot. | ||
// | ||
// To implement the early bailout, we need to track some things on a mutable | ||
// object. Usually, we would put that in a useRef hook, but we can stash it in | ||
// our useState hook instead. | ||
// | ||
// To force a re-render, we call forceUpdate({inst}). That works because the | ||
// new object always fails an equality check. | ||
var _useState = useState({ | ||
inst: { | ||
value: value, | ||
getSnapshot: getSnapshot | ||
} | ||
}), | ||
inst = _useState[0].inst, | ||
forceUpdate = _useState[1]; // Track the latest getSnapshot function with a ref. This needs to be updated | ||
// in the layout phase so we can access it during the tearing check that | ||
// happens on subscribe. | ||
useLayoutEffect(function () { | ||
inst.value = value; | ||
inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the | ||
// commit phase if there was an interleaved mutation. In concurrent mode | ||
// this can happen all the time, but even in synchronous mode, an earlier | ||
// effect may have mutated the store. | ||
if (checkIfSnapshotChanged(inst)) { | ||
// Force a re-render. | ||
forceUpdate({ | ||
inst: inst | ||
}); | ||
} | ||
}, [subscribe, value, getSnapshot]); | ||
useEffect(function () { | ||
// Check for changes right before subscribing. Subsequent changes will be | ||
// detected in the subscription handler. | ||
if (checkIfSnapshotChanged(inst)) { | ||
// Force a re-render. | ||
forceUpdate({ | ||
inst: inst | ||
}); | ||
} | ||
var handleStoreChange = function () { | ||
// TODO: Because there is no cross-renderer API for batching updates, it's | ||
// up to the consumer of this library to wrap their subscription event | ||
// with unstable_batchedUpdates. Should we try to detect when this isn't | ||
// the case and print a warning in development? | ||
// The store changed. Check if the snapshot changed since the last time we | ||
// read from the store. | ||
if (checkIfSnapshotChanged(inst)) { | ||
// Force a re-render. | ||
forceUpdate({ | ||
inst: inst | ||
}); | ||
} | ||
}; // Subscribe to the store and return a clean-up function. | ||
return subscribe(handleStoreChange); | ||
}, [subscribe]); | ||
useDebugValue(value); | ||
return value; | ||
} | ||
function checkIfSnapshotChanged(inst) { | ||
var latestGetSnapshot = inst.getSnapshot; | ||
var prevValue = inst.value; | ||
try { | ||
var nextValue = latestGetSnapshot(); | ||
return !objectIs(prevValue, nextValue); | ||
} catch (error) { | ||
return true; | ||
} | ||
} | ||
function useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) { | ||
// Note: The shim does not use getServerSnapshot, because pre-18 versions of | ||
// React do not expose a way to check if we're hydrating. So users of the shim | ||
// will need to track that themselves and return the correct value | ||
// from `getSnapshot`. | ||
return getSnapshot(); | ||
} | ||
var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined'); | ||
var isServerEnvironment = !canUseDOM; | ||
var shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore; | ||
var useSyncExternalStore$2 = React$1.useSyncExternalStore !== undefined ? React$1.useSyncExternalStore : shim; | ||
useSyncExternalStoreShim_development.useSyncExternalStore = useSyncExternalStore$2; | ||
/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ | ||
if ( | ||
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && | ||
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === | ||
'function' | ||
) { | ||
__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); | ||
} | ||
})(); | ||
} | ||
return useSyncExternalStoreShim_development; | ||
} | ||
var hasRequiredShim; | ||
function requireShim () { | ||
if (hasRequiredShim) return shim.exports; | ||
hasRequiredShim = 1; | ||
if (process.env.NODE_ENV === 'production') { | ||
shim.exports = requireUseSyncExternalStoreShim_production_min(); | ||
} else { | ||
shim.exports = requireUseSyncExternalStoreShim_development(); | ||
} | ||
return shim.exports; | ||
} | ||
/** | ||
* @license React | ||
* use-sync-external-store-shim/with-selector.production.min.js | ||
* | ||
* Copyright (c) Facebook, Inc. and its affiliates. | ||
* | ||
* This source code is licensed under the MIT license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
*/ | ||
var hasRequiredWithSelector_production_min; | ||
function requireWithSelector_production_min () { | ||
if (hasRequiredWithSelector_production_min) return withSelector_production_min; | ||
hasRequiredWithSelector_production_min = 1; | ||
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; | ||
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]); | ||
u(function(){f.hasValue=!0;f.value=d;},[d]);w(d);return d}; | ||
return withSelector_production_min; | ||
} | ||
var withSelector_development = {}; | ||
/** | ||
* @license React | ||
* use-sync-external-store-shim/with-selector.development.js | ||
* | ||
* Copyright (c) Facebook, Inc. and its affiliates. | ||
* | ||
* This source code is licensed under the MIT license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
*/ | ||
var hasRequiredWithSelector_development; | ||
function requireWithSelector_development () { | ||
if (hasRequiredWithSelector_development) return withSelector_development; | ||
hasRequiredWithSelector_development = 1; | ||
if (process.env.NODE_ENV !== "production") { | ||
(function() { | ||
/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ | ||
if ( | ||
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && | ||
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === | ||
'function' | ||
) { | ||
__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); | ||
} | ||
var React$1 = React; | ||
var shim = requireShim(); | ||
/** | ||
* inlined Object.is polyfill to avoid requiring consumers ship their own | ||
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is | ||
*/ | ||
function is(x, y) { | ||
return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare | ||
; | ||
} | ||
var objectIs = typeof Object.is === 'function' ? Object.is : is; | ||
var useSyncExternalStore = shim.useSyncExternalStore; | ||
// for CommonJS interop. | ||
var useRef = React$1.useRef, | ||
useEffect = React$1.useEffect, | ||
useMemo = React$1.useMemo, | ||
useDebugValue = React$1.useDebugValue; // Same as useSyncExternalStore, but supports selector and isEqual arguments. | ||
function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) { | ||
// Use this to track the rendered snapshot. | ||
var instRef = useRef(null); | ||
var inst; | ||
if (instRef.current === null) { | ||
inst = { | ||
hasValue: false, | ||
value: null | ||
}; | ||
instRef.current = inst; | ||
} else { | ||
inst = instRef.current; | ||
} | ||
var _useMemo = useMemo(function () { | ||
// Track the memoized state using closure variables that are local to this | ||
// memoized instance of a getSnapshot function. Intentionally not using a | ||
// useRef hook, because that state would be shared across all concurrent | ||
// copies of the hook/component. | ||
var hasMemo = false; | ||
var memoizedSnapshot; | ||
var memoizedSelection; | ||
var memoizedSelector = function (nextSnapshot) { | ||
if (!hasMemo) { | ||
// The first time the hook is called, there is no memoized result. | ||
hasMemo = true; | ||
memoizedSnapshot = nextSnapshot; | ||
var _nextSelection = selector(nextSnapshot); | ||
if (isEqual !== undefined) { | ||
// Even if the selector has changed, the currently rendered selection | ||
// may be equal to the new selection. We should attempt to reuse the | ||
// current value if possible, to preserve downstream memoizations. | ||
if (inst.hasValue) { | ||
var currentSelection = inst.value; | ||
if (isEqual(currentSelection, _nextSelection)) { | ||
memoizedSelection = currentSelection; | ||
return currentSelection; | ||
} | ||
} | ||
} | ||
memoizedSelection = _nextSelection; | ||
return _nextSelection; | ||
} // We may be able to reuse the previous invocation's result. | ||
// We may be able to reuse the previous invocation's result. | ||
var prevSnapshot = memoizedSnapshot; | ||
var prevSelection = memoizedSelection; | ||
if (objectIs(prevSnapshot, nextSnapshot)) { | ||
// The snapshot is the same as last time. Reuse the previous selection. | ||
return prevSelection; | ||
} // The snapshot has changed, so we need to compute a new selection. | ||
// The snapshot has changed, so we need to compute a new selection. | ||
var nextSelection = selector(nextSnapshot); // If a custom isEqual function is provided, use that to check if the data | ||
// has changed. If it hasn't, return the previous selection. That signals | ||
// to React that the selections are conceptually equal, and we can bail | ||
// out of rendering. | ||
// If a custom isEqual function is provided, use that to check if the data | ||
// has changed. If it hasn't, return the previous selection. That signals | ||
// to React that the selections are conceptually equal, and we can bail | ||
// out of rendering. | ||
if (isEqual !== undefined && isEqual(prevSelection, nextSelection)) { | ||
return prevSelection; | ||
} | ||
memoizedSnapshot = nextSnapshot; | ||
memoizedSelection = nextSelection; | ||
return nextSelection; | ||
}; // Assigning this to a constant so that Flow knows it can't change. | ||
// Assigning this to a constant so that Flow knows it can't change. | ||
var maybeGetServerSnapshot = getServerSnapshot === undefined ? null : getServerSnapshot; | ||
var getSnapshotWithSelector = function () { | ||
return memoizedSelector(getSnapshot()); | ||
}; | ||
var getServerSnapshotWithSelector = maybeGetServerSnapshot === null ? undefined : function () { | ||
return memoizedSelector(maybeGetServerSnapshot()); | ||
}; | ||
return [getSnapshotWithSelector, getServerSnapshotWithSelector]; | ||
}, [getSnapshot, getServerSnapshot, selector, isEqual]), | ||
getSelection = _useMemo[0], | ||
getServerSelection = _useMemo[1]; | ||
var value = useSyncExternalStore(subscribe, getSelection, getServerSelection); | ||
useEffect(function () { | ||
inst.hasValue = true; | ||
inst.value = value; | ||
}, [value]); | ||
useDebugValue(value); | ||
return value; | ||
} | ||
withSelector_development.useSyncExternalStoreWithSelector = useSyncExternalStoreWithSelector; | ||
/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ | ||
if ( | ||
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && | ||
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === | ||
'function' | ||
) { | ||
__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); | ||
} | ||
})(); | ||
} | ||
return withSelector_development; | ||
} | ||
if (process.env.NODE_ENV === 'production') { | ||
withSelector.exports = requireWithSelector_production_min(); | ||
} else { | ||
withSelector.exports = requireWithSelector_development(); | ||
} | ||
var withSelectorExports = withSelector.exports; | ||
/** | ||
* To synchronize the editor instance with the component state, | ||
* we need to create a separate instance that is not affected by the component re-renders. | ||
*/ | ||
function makeEditorStateInstance(initialEditor) { | ||
let transactionNumber = 0; | ||
let lastTransactionNumber = 0; | ||
let lastSnapshot = { editor: initialEditor, transactionNumber: 0 }; | ||
let editor = initialEditor; | ||
const subscribers = new Set(); | ||
const editorInstance = { | ||
/** | ||
* Get the current editor instance. | ||
*/ | ||
getSnapshot() { | ||
if (transactionNumber === lastTransactionNumber) { | ||
return lastSnapshot; | ||
} | ||
lastTransactionNumber = transactionNumber; | ||
lastSnapshot = { editor, transactionNumber }; | ||
return lastSnapshot; | ||
}, | ||
/** | ||
* Always disable the editor on the server-side. | ||
*/ | ||
getServerSnapshot() { | ||
return { editor: null, transactionNumber: 0 }; | ||
}, | ||
/** | ||
* Subscribe to the editor instance's changes. | ||
*/ | ||
subscribe(callback) { | ||
subscribers.add(callback); | ||
return () => { | ||
subscribers.delete(callback); | ||
}; | ||
}, | ||
/** | ||
* Watch the editor instance for changes. | ||
*/ | ||
watch(nextEditor) { | ||
editor = nextEditor; | ||
if (editor) { | ||
/** | ||
* This will force a re-render when the editor state changes. | ||
* This is to support things like `editor.can().toggleBold()` in components that `useEditor`. | ||
* This could be more efficient, but it's a good trade-off for now. | ||
*/ | ||
const fn = () => { | ||
transactionNumber += 1; | ||
subscribers.forEach(callback => callback()); | ||
}; | ||
const currentEditor = editor; | ||
currentEditor.on('transaction', fn); | ||
return () => { | ||
currentEditor.off('transaction', fn); | ||
}; | ||
} | ||
}, | ||
}; | ||
return editorInstance; | ||
} | ||
function useEditorState(options) { | ||
const [editorInstance] = React.useState(() => makeEditorStateInstance(options.editor)); | ||
// Using the `useSyncExternalStore` hook to sync the editor instance with the component state | ||
const selectedState = withSelectorExports.useSyncExternalStoreWithSelector(editorInstance.subscribe, editorInstance.getSnapshot, editorInstance.getServerSnapshot, options.selector, options.equalityFn); | ||
React.useEffect(() => { | ||
return editorInstance.watch(options.editor); | ||
}, [options.editor]); | ||
React.useDebugValue(selectedState); | ||
return selectedState; | ||
} | ||
const isDev = process.env.NODE_ENV !== 'production'; | ||
const isSSR = typeof window === 'undefined'; | ||
const isNext = isSSR || Boolean(typeof window !== 'undefined' && window.next); | ||
function useEditor(options = {}, deps = []) { | ||
const [editor, setEditor] = React.useState(() => { | ||
if (options.immediatelyRender === undefined) { | ||
if (isSSR || isNext) { | ||
// TODO in the next major release, we should throw an error here | ||
if (isDev) { | ||
/** | ||
* Throw an error in development, to make sure the developer is aware that tiptap cannot be SSR'd | ||
* and that they need to set `immediatelyRender` to `false` to avoid hydration mismatches. | ||
*/ | ||
console.warn('Tiptap Error: SSR has been detected, please set `immediatelyRender` explicitly to `false` to avoid hydration mismatches.'); | ||
} | ||
// Best faith effort in production, run the code in the legacy mode to avoid hydration mismatches and errors in production | ||
return null; | ||
} | ||
// Default to immediately rendering when client-side rendering | ||
return new Editor(options); | ||
} | ||
if (options.immediatelyRender && isSSR && isDev) { | ||
// Warn in development, to make sure the developer is aware that tiptap cannot be SSR'd, set `immediatelyRender` to `false` to avoid hydration mismatches. | ||
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.'); | ||
} | ||
if (options.immediatelyRender) { | ||
return new Editor(options); | ||
} | ||
return null; | ||
}); | ||
React.useDebugValue(editor); | ||
// This effect will handle creating/updating the editor instance | ||
React.useEffect(() => { | ||
let editorInstance = editor; | ||
if (!editorInstance) { | ||
editorInstance = new Editor(options); | ||
// instantiate the editor if it doesn't exist | ||
// for ssr, this is the first time the editor is created | ||
setEditor(editorInstance); | ||
} | ||
else { | ||
// if the editor does exist, update the editor options accordingly | ||
editorInstance.setOptions(options); | ||
} | ||
}, deps); | ||
const { onBeforeCreate, onBlur, onCreate, onDestroy, onFocus, onSelectionUpdate, onTransaction, onUpdate, onContentError, } = options; | ||
@@ -159,71 +756,94 @@ const onBeforeCreateRef = React.useRef(onBeforeCreate); | ||
React.useEffect(() => { | ||
if (!editorRef.current) { | ||
if (!editor) { | ||
return; | ||
} | ||
if (onBeforeCreate) { | ||
editorRef.current.off('beforeCreate', onBeforeCreateRef.current); | ||
editorRef.current.on('beforeCreate', onBeforeCreate); | ||
editor.off('beforeCreate', onBeforeCreateRef.current); | ||
editor.on('beforeCreate', onBeforeCreate); | ||
onBeforeCreateRef.current = onBeforeCreate; | ||
} | ||
if (onBlur) { | ||
editorRef.current.off('blur', onBlurRef.current); | ||
editorRef.current.on('blur', onBlur); | ||
editor.off('blur', onBlurRef.current); | ||
editor.on('blur', onBlur); | ||
onBlurRef.current = onBlur; | ||
} | ||
if (onCreate) { | ||
editorRef.current.off('create', onCreateRef.current); | ||
editorRef.current.on('create', onCreate); | ||
editor.off('create', onCreateRef.current); | ||
editor.on('create', onCreate); | ||
onCreateRef.current = onCreate; | ||
} | ||
if (onDestroy) { | ||
editorRef.current.off('destroy', onDestroyRef.current); | ||
editorRef.current.on('destroy', onDestroy); | ||
editor.off('destroy', onDestroyRef.current); | ||
editor.on('destroy', onDestroy); | ||
onDestroyRef.current = onDestroy; | ||
} | ||
if (onFocus) { | ||
editorRef.current.off('focus', onFocusRef.current); | ||
editorRef.current.on('focus', onFocus); | ||
editor.off('focus', onFocusRef.current); | ||
editor.on('focus', onFocus); | ||
onFocusRef.current = onFocus; | ||
} | ||
if (onSelectionUpdate) { | ||
editorRef.current.off('selectionUpdate', onSelectionUpdateRef.current); | ||
editorRef.current.on('selectionUpdate', onSelectionUpdate); | ||
editor.off('selectionUpdate', onSelectionUpdateRef.current); | ||
editor.on('selectionUpdate', onSelectionUpdate); | ||
onSelectionUpdateRef.current = onSelectionUpdate; | ||
} | ||
if (onTransaction) { | ||
editorRef.current.off('transaction', onTransactionRef.current); | ||
editorRef.current.on('transaction', onTransaction); | ||
editor.off('transaction', onTransactionRef.current); | ||
editor.on('transaction', onTransaction); | ||
onTransactionRef.current = onTransaction; | ||
} | ||
if (onUpdate) { | ||
editorRef.current.off('update', onUpdateRef.current); | ||
editorRef.current.on('update', onUpdate); | ||
editor.off('update', onUpdateRef.current); | ||
editor.on('update', onUpdate); | ||
onUpdateRef.current = onUpdate; | ||
} | ||
if (onContentError) { | ||
editorRef.current.off('contentError', onContentErrorRef.current); | ||
editorRef.current.on('contentError', onContentError); | ||
editor.off('contentError', onContentErrorRef.current); | ||
editor.on('contentError', onContentError); | ||
onContentErrorRef.current = onContentError; | ||
} | ||
}, [onBeforeCreate, onBlur, onCreate, onDestroy, onFocus, onSelectionUpdate, onTransaction, onUpdate, editorRef.current]); | ||
}, [ | ||
onBeforeCreate, | ||
onBlur, | ||
onCreate, | ||
onDestroy, | ||
onFocus, | ||
onSelectionUpdate, | ||
onTransaction, | ||
onUpdate, | ||
onContentError, | ||
editor, | ||
]); | ||
/** | ||
* Destroy the editor instance when the component completely unmounts | ||
* As opposed to the cleanup function in the effect above, this will | ||
* only be called when the component is removed from the DOM, since it has no deps. | ||
* */ | ||
React.useEffect(() => { | ||
let isMounted = true; | ||
const editor = new Editor(options); | ||
editorRef.current = editor; | ||
editorRef.current.on('transaction', () => { | ||
requestAnimationFrame(() => { | ||
requestAnimationFrame(() => { | ||
if (isMounted) { | ||
forceUpdate({}); | ||
} | ||
}); | ||
}); | ||
}); | ||
return () => { | ||
isMounted = false; | ||
editor.destroy(); | ||
if (editor) { | ||
// We need to destroy the editor asynchronously to avoid memory leaks | ||
// because the editor instance is still being used in the component. | ||
setTimeout(() => (editor.isDestroyed ? null : editor.destroy())); | ||
} | ||
}; | ||
}, deps); | ||
return editorRef.current; | ||
}; | ||
}, []); | ||
// The default behavior is to re-render on each transaction | ||
// This is legacy behavior that will be removed in future versions | ||
useEditorState({ | ||
editor, | ||
selector: ({ transactionNumber }) => { | ||
if (options.shouldRerenderOnTransaction === false) { | ||
// This will prevent the editor from re-rendering on each transaction | ||
return null; | ||
} | ||
// This will avoid re-rendering on the first transaction when `immediatelyRender` is set to `true` | ||
if (options.immediatelyRender && transactionNumber === 0) { | ||
return 0; | ||
} | ||
return transactionNumber + 1; | ||
}, | ||
}); | ||
return editor; | ||
} | ||
@@ -234,4 +854,12 @@ const EditorContext = React.createContext({ | ||
const EditorConsumer = EditorContext.Consumer; | ||
/** | ||
* A hook to get the current editor instance. | ||
*/ | ||
const useCurrentEditor = () => React.useContext(EditorContext); | ||
const EditorProvider = ({ children, slotAfter, slotBefore, ...editorOptions }) => { | ||
/** | ||
* This is the provider component for the editor. | ||
* It allows the editor to be accessible across the entire component tree | ||
* with `useCurrentEditor`. | ||
*/ | ||
function EditorProvider({ children, slotAfter, slotBefore, ...editorOptions }) { | ||
const editor = useEditor(editorOptions); | ||
@@ -246,3 +874,3 @@ if (!editor) { | ||
slotAfter)); | ||
}; | ||
} | ||
@@ -575,2 +1203,3 @@ const BubbleMenu = (props) => { | ||
exports.useEditor = useEditor; | ||
exports.useEditorState = useEditorState; | ||
exports.useReactNodeView = useReactNodeView; | ||
@@ -577,0 +1206,0 @@ Object.keys(core).forEach(function (k) { |
@@ -1,4 +0,4 @@ | ||
import { EditorOptions } from '@tiptap/core'; | ||
import React, { ReactNode } from 'react'; | ||
import { Editor } from './Editor.js'; | ||
import { UseEditorOptions } from './useEditor.js'; | ||
export type EditorContextValue = { | ||
@@ -9,2 +9,5 @@ editor: Editor | null; | ||
export declare const EditorConsumer: React.Consumer<EditorContextValue>; | ||
/** | ||
* A hook to get the current editor instance. | ||
*/ | ||
export declare const useCurrentEditor: () => EditorContextValue; | ||
@@ -15,3 +18,8 @@ export type EditorProviderProps = { | ||
slotAfter?: ReactNode; | ||
} & Partial<EditorOptions>; | ||
export declare const EditorProvider: ({ children, slotAfter, slotBefore, ...editorOptions }: EditorProviderProps) => React.JSX.Element | null; | ||
} & UseEditorOptions; | ||
/** | ||
* This is the provider component for the editor. | ||
* It allows the editor to be accessible across the entire component tree | ||
* with `useCurrentEditor`. | ||
*/ | ||
export declare function EditorProvider({ children, slotAfter, slotBefore, ...editorOptions }: EditorProviderProps): React.JSX.Element | null; |
@@ -11,3 +11,4 @@ export * from './BubbleMenu.js'; | ||
export * from './useEditor.js'; | ||
export * from './useEditorState.js'; | ||
export * from './useReactNodeView.js'; | ||
export * from '@tiptap/core'; |
@@ -5,2 +5,20 @@ import { EditorOptions } from '@tiptap/core'; | ||
/** | ||
* The options for the `useEditor` hook. | ||
*/ | ||
export type UseEditorOptions = Partial<EditorOptions> & { | ||
/** | ||
* Whether to render the editor on the first render. | ||
* If client-side rendering, set this to `true`. | ||
* If server-side rendering, set this to `false`. | ||
* @default true | ||
*/ | ||
immediatelyRender?: boolean; | ||
/** | ||
* Whether to re-render the editor on each transaction. | ||
* This is legacy behavior that will be removed in future versions. | ||
* @default true | ||
*/ | ||
shouldRerenderOnTransaction?: boolean; | ||
}; | ||
/** | ||
* This hook allows you to create an editor instance. | ||
@@ -12,2 +30,12 @@ * @param options The editor options | ||
*/ | ||
export declare const useEditor: (options?: Partial<EditorOptions>, deps?: DependencyList) => Editor | null; | ||
export declare function useEditor(options: UseEditorOptions & { | ||
immediatelyRender: true; | ||
}, deps?: DependencyList): Editor; | ||
/** | ||
* This hook allows you to create an editor instance. | ||
* @param options The editor options | ||
* @param deps The dependencies to watch for changes | ||
* @returns The editor instance | ||
* @example const editor = useEditor({ extensions: [...] }) | ||
*/ | ||
export declare function useEditor(options?: UseEditorOptions, deps?: DependencyList): Editor | null; |
{ | ||
"name": "@tiptap/react", | ||
"description": "React components for tiptap", | ||
"version": "2.5.0-pre.13", | ||
"version": "2.5.0-pre.14", | ||
"homepage": "https://tiptap.dev", | ||
@@ -32,8 +32,10 @@ "keywords": [ | ||
"dependencies": { | ||
"@tiptap/extension-bubble-menu": "^2.5.0-pre.13", | ||
"@tiptap/extension-floating-menu": "^2.5.0-pre.13" | ||
"@tiptap/extension-bubble-menu": "^2.5.0-pre.14", | ||
"@tiptap/extension-floating-menu": "^2.5.0-pre.14", | ||
"use-sync-external-store": "^1.2.2", | ||
"@types/use-sync-external-store": "^0.0.6" | ||
}, | ||
"devDependencies": { | ||
"@tiptap/core": "^2.5.0-pre.13", | ||
"@tiptap/pm": "^2.5.0-pre.13", | ||
"@tiptap/core": "^2.5.0-pre.14", | ||
"@tiptap/pm": "^2.5.0-pre.14", | ||
"@types/react": "^18.2.14", | ||
@@ -45,4 +47,4 @@ "@types/react-dom": "^18.2.6", | ||
"peerDependencies": { | ||
"@tiptap/core": "^2.5.0-pre.13", | ||
"@tiptap/pm": "^2.5.0-pre.13", | ||
"@tiptap/core": "^2.5.0-pre.14", | ||
"@tiptap/pm": "^2.5.0-pre.14", | ||
"react": "^17.0.0 || ^18.0.0", | ||
@@ -49,0 +51,0 @@ "react-dom": "^17.0.0 || ^18.0.0" |
@@ -11,3 +11,4 @@ export * from './BubbleMenu.js' | ||
export * from './useEditor.js' | ||
export * from './useEditorState.js' | ||
export * from './useReactNodeView.js' | ||
export * from '@tiptap/core' |
import { EditorOptions } from '@tiptap/core' | ||
import { | ||
DependencyList, | ||
useEffect, | ||
useRef, | ||
useState, | ||
DependencyList, useDebugValue, useEffect, useRef, useState, | ||
} from 'react' | ||
import { Editor } from './Editor.js' | ||
import { useEditorState } from './useEditorState.js' | ||
const isDev = process.env.NODE_ENV !== 'production' | ||
const isSSR = typeof window === 'undefined' | ||
const isNext = isSSR || Boolean(typeof window !== 'undefined' && (window as any).next) | ||
/** | ||
* The options for the `useEditor` hook. | ||
*/ | ||
export type UseEditorOptions = Partial<EditorOptions> & { | ||
/** | ||
* Whether to render the editor on the first render. | ||
* If client-side rendering, set this to `true`. | ||
* If server-side rendering, set this to `false`. | ||
* @default true | ||
*/ | ||
immediatelyRender?: boolean; | ||
/** | ||
* Whether to re-render the editor on each transaction. | ||
* This is legacy behavior that will be removed in future versions. | ||
* @default true | ||
*/ | ||
shouldRerenderOnTransaction?: boolean; | ||
}; | ||
/** | ||
* This hook allows you to create an editor instance. | ||
@@ -18,6 +39,76 @@ * @param options The editor options | ||
*/ | ||
export const useEditor = (options: Partial<EditorOptions> = {}, deps: DependencyList = []) => { | ||
const editorRef = useRef<Editor | null>(null) | ||
const [, forceUpdate] = useState({}) | ||
export function useEditor( | ||
options: UseEditorOptions & { immediatelyRender: true }, | ||
deps?: DependencyList | ||
): Editor; | ||
/** | ||
* This hook allows you to create an editor instance. | ||
* @param options The editor options | ||
* @param deps The dependencies to watch for changes | ||
* @returns The editor instance | ||
* @example const editor = useEditor({ extensions: [...] }) | ||
*/ | ||
export function useEditor( | ||
options?: UseEditorOptions, | ||
deps?: DependencyList | ||
): Editor | null; | ||
export function useEditor( | ||
options: UseEditorOptions = {}, | ||
deps: DependencyList = [], | ||
): Editor | null { | ||
const [editor, setEditor] = useState(() => { | ||
if (options.immediatelyRender === undefined) { | ||
if (isSSR || isNext) { | ||
// TODO in the next major release, we should throw an error here | ||
if (isDev) { | ||
/** | ||
* Throw an error in development, to make sure the developer is aware that tiptap cannot be SSR'd | ||
* and that they need to set `immediatelyRender` to `false` to avoid hydration mismatches. | ||
*/ | ||
console.warn( | ||
'Tiptap Error: SSR has been detected, please set `immediatelyRender` explicitly to `false` to avoid hydration mismatches.', | ||
) | ||
} | ||
// Best faith effort in production, run the code in the legacy mode to avoid hydration mismatches and errors in production | ||
return null | ||
} | ||
// Default to immediately rendering when client-side rendering | ||
return new Editor(options) | ||
} | ||
if (options.immediatelyRender && isSSR && isDev) { | ||
// Warn in development, to make sure the developer is aware that tiptap cannot be SSR'd, set `immediatelyRender` to `false` to avoid hydration mismatches. | ||
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.', | ||
) | ||
} | ||
if (options.immediatelyRender) { | ||
return new Editor(options) | ||
} | ||
return null | ||
}) | ||
useDebugValue(editor) | ||
// This effect will handle creating/updating the editor instance | ||
useEffect(() => { | ||
let editorInstance: Editor | null = editor | ||
if (!editorInstance) { | ||
editorInstance = new Editor(options) | ||
// instantiate the editor if it doesn't exist | ||
// for ssr, this is the first time the editor is created | ||
setEditor(editorInstance) | ||
} else { | ||
// if the editor does exist, update the editor options accordingly | ||
editorInstance.setOptions(options) | ||
} | ||
}, deps) | ||
const { | ||
@@ -48,3 +139,3 @@ onBeforeCreate, | ||
useEffect(() => { | ||
if (!editorRef.current) { | ||
if (!editor) { | ||
return | ||
@@ -54,4 +145,4 @@ } | ||
if (onBeforeCreate) { | ||
editorRef.current.off('beforeCreate', onBeforeCreateRef.current) | ||
editorRef.current.on('beforeCreate', onBeforeCreate) | ||
editor.off('beforeCreate', onBeforeCreateRef.current) | ||
editor.on('beforeCreate', onBeforeCreate) | ||
@@ -62,4 +153,4 @@ onBeforeCreateRef.current = onBeforeCreate | ||
if (onBlur) { | ||
editorRef.current.off('blur', onBlurRef.current) | ||
editorRef.current.on('blur', onBlur) | ||
editor.off('blur', onBlurRef.current) | ||
editor.on('blur', onBlur) | ||
@@ -70,4 +161,4 @@ onBlurRef.current = onBlur | ||
if (onCreate) { | ||
editorRef.current.off('create', onCreateRef.current) | ||
editorRef.current.on('create', onCreate) | ||
editor.off('create', onCreateRef.current) | ||
editor.on('create', onCreate) | ||
@@ -78,4 +169,4 @@ onCreateRef.current = onCreate | ||
if (onDestroy) { | ||
editorRef.current.off('destroy', onDestroyRef.current) | ||
editorRef.current.on('destroy', onDestroy) | ||
editor.off('destroy', onDestroyRef.current) | ||
editor.on('destroy', onDestroy) | ||
@@ -86,4 +177,4 @@ onDestroyRef.current = onDestroy | ||
if (onFocus) { | ||
editorRef.current.off('focus', onFocusRef.current) | ||
editorRef.current.on('focus', onFocus) | ||
editor.off('focus', onFocusRef.current) | ||
editor.on('focus', onFocus) | ||
@@ -94,4 +185,4 @@ onFocusRef.current = onFocus | ||
if (onSelectionUpdate) { | ||
editorRef.current.off('selectionUpdate', onSelectionUpdateRef.current) | ||
editorRef.current.on('selectionUpdate', onSelectionUpdate) | ||
editor.off('selectionUpdate', onSelectionUpdateRef.current) | ||
editor.on('selectionUpdate', onSelectionUpdate) | ||
@@ -102,4 +193,4 @@ onSelectionUpdateRef.current = onSelectionUpdate | ||
if (onTransaction) { | ||
editorRef.current.off('transaction', onTransactionRef.current) | ||
editorRef.current.on('transaction', onTransaction) | ||
editor.off('transaction', onTransactionRef.current) | ||
editor.on('transaction', onTransaction) | ||
@@ -110,4 +201,4 @@ onTransactionRef.current = onTransaction | ||
if (onUpdate) { | ||
editorRef.current.off('update', onUpdateRef.current) | ||
editorRef.current.on('update', onUpdate) | ||
editor.off('update', onUpdateRef.current) | ||
editor.on('update', onUpdate) | ||
@@ -118,33 +209,55 @@ onUpdateRef.current = onUpdate | ||
if (onContentError) { | ||
editorRef.current.off('contentError', onContentErrorRef.current) | ||
editorRef.current.on('contentError', onContentError) | ||
editor.off('contentError', onContentErrorRef.current) | ||
editor.on('contentError', onContentError) | ||
onContentErrorRef.current = onContentError | ||
} | ||
}, [onBeforeCreate, onBlur, onCreate, onDestroy, onFocus, onSelectionUpdate, onTransaction, onUpdate, editorRef.current]) | ||
}, [ | ||
onBeforeCreate, | ||
onBlur, | ||
onCreate, | ||
onDestroy, | ||
onFocus, | ||
onSelectionUpdate, | ||
onTransaction, | ||
onUpdate, | ||
onContentError, | ||
editor, | ||
]) | ||
/** | ||
* Destroy the editor instance when the component completely unmounts | ||
* As opposed to the cleanup function in the effect above, this will | ||
* only be called when the component is removed from the DOM, since it has no deps. | ||
* */ | ||
useEffect(() => { | ||
let isMounted = true | ||
return () => { | ||
if (editor) { | ||
// We need to destroy the editor asynchronously to avoid memory leaks | ||
// because the editor instance is still being used in the component. | ||
const editor = new Editor(options) | ||
setTimeout(() => (editor.isDestroyed ? null : editor.destroy())) | ||
} | ||
} | ||
}, []) | ||
editorRef.current = editor | ||
// The default behavior is to re-render on each transaction | ||
// This is legacy behavior that will be removed in future versions | ||
useEditorState({ | ||
editor, | ||
selector: ({ transactionNumber }) => { | ||
if (options.shouldRerenderOnTransaction === false) { | ||
// This will prevent the editor from re-rendering on each transaction | ||
return null | ||
} | ||
editorRef.current.on('transaction', () => { | ||
requestAnimationFrame(() => { | ||
requestAnimationFrame(() => { | ||
if (isMounted) { | ||
forceUpdate({}) | ||
} | ||
}) | ||
}) | ||
}) | ||
// This will avoid re-rendering on the first transaction when `immediatelyRender` is set to `true` | ||
if (options.immediatelyRender && transactionNumber === 0) { | ||
return 0 | ||
} | ||
return transactionNumber + 1 | ||
}, | ||
}) | ||
return () => { | ||
isMounted = false | ||
editor.destroy() | ||
} | ||
}, deps) | ||
return editorRef.current | ||
return editor | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
577862
201
8470
8
15
+ Added@types/use-sync-external-store@0.0.6(transitive)
+ Addeduse-sync-external-store@1.2.2(transitive)