Socket
Socket
Sign inDemoInstall

@tiptap/react

Package Overview
Dependencies
Maintainers
5
Versions
231
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@tiptap/react - npm Package Compare versions

Comparing version 3.0.0-next.0 to 3.0.0-next.1

dist/index.d.cts

1913

dist/index.js

@@ -1,1153 +0,884 @@

import { BubbleMenuPlugin } from '@tiptap/extension-bubble-menu';
import React, { forwardRef, useState, useEffect, useDebugValue, useRef, createContext, useContext } from 'react';
import ReactDOM, { flushSync, createPortal } from 'react-dom';
import { Editor as Editor$1, NodeView } from '@tiptap/core';
export * from '@tiptap/core';
import { FloatingMenuPlugin } from '@tiptap/extension-floating-menu';
// src/BubbleMenu.tsx
import { BubbleMenuPlugin } from "@tiptap/extension-bubble-menu";
import React3, { useEffect as useEffect3, useRef as useRef2 } from "react";
import { createPortal } from "react-dom";
const mergeRefs = (...refs) => {
return (node) => {
refs.forEach(ref => {
if (typeof ref === 'function') {
ref(node);
}
else if (ref) {
ref.current = node;
}
});
};
// src/Context.tsx
import React2, { createContext, useContext } from "react";
// src/EditorContent.tsx
import React, {
forwardRef
} from "react";
import ReactDOM from "react-dom";
import { useSyncExternalStore } from "use-sync-external-store/shim";
var mergeRefs = (...refs) => {
return (node) => {
refs.forEach((ref) => {
if (typeof ref === "function") {
ref(node);
} else if (ref) {
ref.current = node;
}
});
};
};
const Portals = ({ renderers }) => {
return (React.createElement(React.Fragment, null, Object.entries(renderers).map(([key, renderer]) => {
return ReactDOM.createPortal(renderer.reactElement, renderer.element, key);
})));
var Portals = ({
contentComponent
}) => {
const renderers = useSyncExternalStore(
contentComponent.subscribe,
contentComponent.getSnapshot,
contentComponent.getServerSnapshot
);
return /* @__PURE__ */ React.createElement(React.Fragment, null, Object.values(renderers));
};
class PureEditorContent extends React.Component {
constructor(props) {
super(props);
this.editorContentRef = React.createRef();
this.initialized = false;
this.state = {
renderers: {},
};
function getInstance() {
const subscribers = /* @__PURE__ */ new Set();
let renderers = {};
return {
/**
* Subscribe to the editor instance's changes.
*/
subscribe(callback) {
subscribers.add(callback);
return () => {
subscribers.delete(callback);
};
},
getSnapshot() {
return renderers;
},
getServerSnapshot() {
return renderers;
},
/**
* Adds a new NodeView Renderer to the editor.
*/
setRenderer(id, renderer) {
renderers = {
...renderers,
[id]: ReactDOM.createPortal(renderer.reactElement, renderer.element, id)
};
subscribers.forEach((subscriber) => subscriber());
},
/**
* Removes a NodeView Renderer from the editor.
*/
removeRenderer(id) {
const nextRenderers = { ...renderers };
delete nextRenderers[id];
renderers = nextRenderers;
subscribers.forEach((subscriber) => subscriber());
}
componentDidMount() {
this.init();
}
componentDidUpdate() {
this.init();
}
init() {
const { editor } = this.props;
if (editor && !editor.isDestroyed && editor.options.element) {
if (editor.contentComponent) {
return;
};
}
var PureEditorContent = class extends React.Component {
constructor(props) {
var _a;
super(props);
this.editorContentRef = React.createRef();
this.initialized = false;
this.state = {
hasContentComponentInitialized: Boolean((_a = props.editor) == null ? void 0 : _a.contentComponent)
};
}
componentDidMount() {
this.init();
}
componentDidUpdate() {
this.init();
}
init() {
const editor = this.props.editor;
if (editor && !editor.isDestroyed && editor.options.element) {
if (editor.contentComponent) {
return;
}
const element = this.editorContentRef.current;
element.append(...editor.options.element.childNodes);
editor.setOptions({
element
});
editor.contentComponent = getInstance();
if (!this.state.hasContentComponentInitialized) {
this.unsubscribeToContentComponent = editor.contentComponent.subscribe(() => {
this.setState((prevState) => {
if (!prevState.hasContentComponentInitialized) {
return {
hasContentComponentInitialized: true
};
}
const element = this.editorContentRef.current;
element.append(...editor.options.element.childNodes);
editor.setOptions({
element,
});
editor.contentComponent = this;
editor.createNodeViews();
this.initialized = true;
}
return prevState;
});
if (this.unsubscribeToContentComponent) {
this.unsubscribeToContentComponent();
}
});
}
editor.createNodeViews();
this.initialized = true;
}
maybeFlushSync(fn) {
// Avoid calling flushSync until the editor is initialized.
// Initialization happens during the componentDidMount or componentDidUpdate
// lifecycle methods, and React doesn't allow calling flushSync from inside
// a lifecycle method.
if (this.initialized) {
flushSync(fn);
}
else {
fn();
}
}
componentWillUnmount() {
const editor = this.props.editor;
if (!editor) {
return;
}
setRenderer(id, renderer) {
this.maybeFlushSync(() => {
this.setState(({ renderers }) => ({
renderers: {
...renderers,
[id]: renderer,
},
}));
});
this.initialized = false;
if (!editor.isDestroyed) {
editor.view.setProps({
nodeViews: {}
});
}
removeRenderer(id) {
this.maybeFlushSync(() => {
this.setState(({ renderers }) => {
const nextRenderers = { ...renderers };
delete nextRenderers[id];
return { renderers: nextRenderers };
});
});
if (this.unsubscribeToContentComponent) {
this.unsubscribeToContentComponent();
}
componentWillUnmount() {
const { editor } = this.props;
if (!editor) {
return;
}
this.initialized = false;
if (!editor.isDestroyed) {
editor.view.setProps({
nodeViews: {},
});
}
editor.contentComponent = null;
if (!editor.options.element.firstChild) {
return;
}
const newElement = document.createElement('div');
newElement.append(...editor.options.element.childNodes);
editor.setOptions({
element: newElement,
});
editor.contentComponent = null;
if (!editor.options.element.firstChild) {
return;
}
render() {
const { editor, innerRef, ...rest } = this.props;
return (React.createElement(React.Fragment, null,
React.createElement("div", { ref: mergeRefs(innerRef, this.editorContentRef), ...rest }),
React.createElement(Portals, { renderers: this.state.renderers })));
}
}
// EditorContent should be re-created whenever the Editor instance changes
const EditorContentWithKey = forwardRef((props, ref) => {
const newElement = document.createElement("div");
newElement.append(...editor.options.element.childNodes);
editor.setOptions({
element: newElement
});
}
render() {
const { editor, innerRef, ...rest } = this.props;
return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { ref: mergeRefs(innerRef, this.editorContentRef), ...rest }), (editor == null ? void 0 : editor.contentComponent) && /* @__PURE__ */ React.createElement(Portals, { contentComponent: editor.contentComponent }));
}
};
var EditorContentWithKey = forwardRef(
(props, ref) => {
const key = React.useMemo(() => {
return Math.floor(Math.random() * 0xFFFFFFFF).toString();
return Math.floor(Math.random() * 4294967295).toString();
}, [props.editor]);
// Can't use JSX here because it conflicts with the type definition of Vue's JSX, so use createElement
return React.createElement(PureEditorContent, {
key,
innerRef: ref,
...props,
key,
innerRef: ref,
...props
});
});
const EditorContent = React.memo(EditorContentWithKey);
}
);
var EditorContent = React.memo(EditorContentWithKey);
class Editor extends Editor$1 {
constructor() {
super(...arguments);
this.contentComponent = null;
// src/useEditor.ts
import { Editor } from "@tiptap/core";
import {
useDebugValue as useDebugValue2,
useEffect as useEffect2,
useRef,
useState as useState2
} from "react";
import { useSyncExternalStore as useSyncExternalStore2 } from "use-sync-external-store/shim";
// src/useEditorState.ts
import { useDebugValue, useEffect, useState } from "react";
import { useSyncExternalStoreWithSelector } from "use-sync-external-store/shim/with-selector";
var EditorStateManager = class {
constructor(initialEditor) {
this.transactionNumber = 0;
this.lastTransactionNumber = 0;
this.subscribers = /* @__PURE__ */ new Set();
this.editor = initialEditor;
this.lastSnapshot = { editor: initialEditor, transactionNumber: 0 };
this.getSnapshot = this.getSnapshot.bind(this);
this.getServerSnapshot = this.getServerSnapshot.bind(this);
this.watch = this.watch.bind(this);
this.subscribe = this.subscribe.bind(this);
}
/**
* Get the current editor instance.
*/
getSnapshot() {
if (this.transactionNumber === this.lastTransactionNumber) {
return this.lastSnapshot;
}
}
var withSelector = {exports: {}};
var withSelector_production_min = {};
var shim = {exports: {}};
var useSyncExternalStoreShim_production_min = {};
/**
* @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.
*/
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);
};
}
},
this.lastTransactionNumber = this.transactionNumber;
this.lastSnapshot = { editor: this.editor, transactionNumber: this.transactionNumber };
return this.lastSnapshot;
}
/**
* Always disable the editor on the server-side.
*/
getServerSnapshot() {
return { editor: null, transactionNumber: 0 };
}
/**
* Subscribe to the editor instance's changes.
*/
subscribe(callback) {
this.subscribers.add(callback);
return () => {
this.subscribers.delete(callback);
};
return editorInstance;
}
}
/**
* Watch the editor instance for changes.
*/
watch(nextEditor) {
this.editor = nextEditor;
if (this.editor) {
const fn = () => {
this.transactionNumber += 1;
this.subscribers.forEach((callback) => callback());
};
const currentEditor = this.editor;
currentEditor.on("transaction", fn);
return () => {
currentEditor.off("transaction", fn);
};
}
return void 0;
}
};
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 [editorInstance] = useState(() => new EditorStateManager(options.editor));
const selectedState = useSyncExternalStoreWithSelector(
editorInstance.subscribe,
editorInstance.getSnapshot,
editorInstance.getServerSnapshot,
options.selector,
options.equalityFn
);
useEffect(() => {
return editorInstance.watch(options.editor);
}, [options.editor, editorInstance]);
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);
/**
* Create a new editor instance. And attach event listeners.
*/
function createEditor(options) {
const editor = new Editor(options.current);
editor.on('beforeCreate', (...args) => { var _a, _b; return (_b = (_a = options.current).onBeforeCreate) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); });
editor.on('blur', (...args) => { var _a, _b; return (_b = (_a = options.current).onBlur) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); });
editor.on('create', (...args) => { var _a, _b; return (_b = (_a = options.current).onCreate) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); });
editor.on('destroy', (...args) => { var _a, _b; return (_b = (_a = options.current).onDestroy) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); });
editor.on('focus', (...args) => { var _a, _b; return (_b = (_a = options.current).onFocus) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); });
editor.on('selectionUpdate', (...args) => { var _a, _b; return (_b = (_a = options.current).onSelectionUpdate) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); });
editor.on('transaction', (...args) => { var _a, _b; return (_b = (_a = options.current).onTransaction) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); });
editor.on('update', (...args) => { var _a, _b; return (_b = (_a = options.current).onUpdate) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); });
editor.on('contentError', (...args) => { var _a, _b; return (_b = (_a = options.current).onContentError) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); });
// src/useEditor.ts
var isDev = process.env.NODE_ENV !== "production";
var isSSR = typeof window === "undefined";
var isNext = isSSR || Boolean(typeof window !== "undefined" && window.next);
var EditorInstanceManager = class {
constructor(options) {
/**
* The current editor instance.
*/
this.editor = null;
/**
* The subscriptions to notify when the editor instance
* has been created or destroyed.
*/
this.subscriptions = /* @__PURE__ */ new Set();
/**
* Whether the editor has been mounted.
*/
this.isComponentMounted = false;
/**
* The most recent dependencies array.
*/
this.previousDeps = null;
/**
* The unique instance ID. This is used to identify the editor instance. And will be re-generated for each new instance.
*/
this.instanceId = "";
this.options = options;
this.subscriptions = /* @__PURE__ */ new Set();
this.setEditor(this.getInitialEditor());
this.getEditor = this.getEditor.bind(this);
this.getServerSnapshot = this.getServerSnapshot.bind(this);
this.subscribe = this.subscribe.bind(this);
this.refreshEditorInstance = this.refreshEditorInstance.bind(this);
this.scheduleDestroy = this.scheduleDestroy.bind(this);
this.onRender = this.onRender.bind(this);
this.createEditor = this.createEditor.bind(this);
}
setEditor(editor) {
this.editor = editor;
this.instanceId = Math.random().toString(36).slice(2, 9);
this.subscriptions.forEach((cb) => cb());
}
getInitialEditor() {
if (this.options.current.immediatelyRender === void 0) {
if (isSSR || isNext) {
if (isDev) {
throw new Error(
"Tiptap Error: SSR has been detected, please set `immediatelyRender` explicitly to `false` to avoid hydration mismatches."
);
}
return null;
}
return this.createEditor();
}
if (this.options.current.immediatelyRender && isSSR && isDev) {
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 (this.options.current.immediatelyRender) {
return this.createEditor();
}
return null;
}
/**
* Create a new editor instance. And attach event listeners.
*/
createEditor() {
const optionsToApply = {
...this.options.current,
// Always call the most recent version of the callback function by default
onBeforeCreate: (...args) => {
var _a, _b;
return (_b = (_a = this.options.current).onBeforeCreate) == null ? void 0 : _b.call(_a, ...args);
},
onBlur: (...args) => {
var _a, _b;
return (_b = (_a = this.options.current).onBlur) == null ? void 0 : _b.call(_a, ...args);
},
onCreate: (...args) => {
var _a, _b;
return (_b = (_a = this.options.current).onCreate) == null ? void 0 : _b.call(_a, ...args);
},
onDestroy: (...args) => {
var _a, _b;
return (_b = (_a = this.options.current).onDestroy) == null ? void 0 : _b.call(_a, ...args);
},
onFocus: (...args) => {
var _a, _b;
return (_b = (_a = this.options.current).onFocus) == null ? void 0 : _b.call(_a, ...args);
},
onSelectionUpdate: (...args) => {
var _a, _b;
return (_b = (_a = this.options.current).onSelectionUpdate) == null ? void 0 : _b.call(_a, ...args);
},
onTransaction: (...args) => {
var _a, _b;
return (_b = (_a = this.options.current).onTransaction) == null ? void 0 : _b.call(_a, ...args);
},
onUpdate: (...args) => {
var _a, _b;
return (_b = (_a = this.options.current).onUpdate) == null ? void 0 : _b.call(_a, ...args);
},
onContentError: (...args) => {
var _a, _b;
return (_b = (_a = this.options.current).onContentError) == null ? void 0 : _b.call(_a, ...args);
}
};
const editor = new Editor(optionsToApply);
return editor;
}
function useEditor(options = {}, deps = []) {
const mostRecentOptions = useRef(options);
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 createEditor(mostRecentOptions);
}
/**
* Get the current editor instance.
*/
getEditor() {
return this.editor;
}
/**
* Always disable the editor on the server-side.
*/
getServerSnapshot() {
return null;
}
/**
* Subscribe to the editor instance's changes.
*/
subscribe(onStoreChange) {
this.subscriptions.add(onStoreChange);
return () => {
this.subscriptions.delete(onStoreChange);
};
}
/**
* On each render, we will create, update, or destroy the editor instance.
* @param deps The dependencies to watch for changes
* @returns A cleanup function
*/
onRender(deps) {
return () => {
this.isComponentMounted = true;
clearTimeout(this.scheduledDestructionTimeout);
if (this.editor && !this.editor.isDestroyed && deps.length === 0) {
this.editor.setOptions(this.options.current);
} else {
this.refreshEditorInstance(deps);
}
return () => {
this.isComponentMounted = false;
this.scheduleDestroy();
};
};
}
/**
* Recreate the editor instance if the dependencies have changed.
*/
refreshEditorInstance(deps) {
if (this.editor && !this.editor.isDestroyed) {
if (this.previousDeps === null) {
this.previousDeps = deps;
return;
}
const depsAreEqual = this.previousDeps.length === deps.length && this.previousDeps.every((dep, index) => dep === deps[index]);
if (depsAreEqual) {
return;
}
}
if (this.editor && !this.editor.isDestroyed) {
this.editor.destroy();
}
this.setEditor(this.createEditor());
this.previousDeps = deps;
}
/**
* Schedule the destruction of the editor instance.
* This will only destroy the editor if it was not mounted on the next tick.
* This is to avoid destroying the editor instance when it's actually still mounted.
*/
scheduleDestroy() {
const currentInstanceId = this.instanceId;
const currentEditor = this.editor;
this.scheduledDestructionTimeout = setTimeout(() => {
if (this.isComponentMounted && this.instanceId === currentInstanceId) {
if (currentEditor) {
currentEditor.setOptions(this.options.current);
}
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.');
return;
}
if (currentEditor && !currentEditor.isDestroyed) {
currentEditor.destroy();
if (this.instanceId === currentInstanceId) {
this.setEditor(null);
}
if (options.immediatelyRender) {
return createEditor(mostRecentOptions);
}
}
}, 0);
}
};
function useEditor(options = {}, deps = []) {
const mostRecentOptions = useRef(options);
mostRecentOptions.current = options;
const [instanceManager] = useState2(() => new EditorInstanceManager(mostRecentOptions));
const editor = useSyncExternalStore2(
instanceManager.subscribe,
instanceManager.getEditor,
instanceManager.getServerSnapshot
);
useDebugValue2(editor);
useEffect2(instanceManager.onRender(deps));
useEditorState({
editor,
selector: ({ transactionNumber }) => {
if (options.shouldRerenderOnTransaction === false) {
return null;
});
const mostRecentEditor = useRef(editor);
mostRecentEditor.current = editor;
useDebugValue(editor);
// This effect will handle creating/updating the editor instance
useEffect(() => {
const destroyUnusedEditor = (editorInstance) => {
if (editorInstance) {
// We need to destroy the editor asynchronously to avoid memory leaks
// because the editor instance is still being used in the component.
setTimeout(() => {
// re-use the editor instance if it hasn't been replaced yet
// otherwise, asynchronously destroy the old editor instance
if (editorInstance !== mostRecentEditor.current && !editorInstance.isDestroyed) {
editorInstance.destroy();
}
});
}
};
let editorInstance = mostRecentEditor.current;
if (!editorInstance) {
editorInstance = createEditor(mostRecentOptions);
setEditor(editorInstance);
return () => destroyUnusedEditor(editorInstance);
}
if (!Array.isArray(deps) || deps.length === 0) {
// if the editor does exist & deps are empty, we don't need to re-initialize the editor
// we can fast-path to update the editor options on the existing instance
editorInstance.setOptions(options);
return () => destroyUnusedEditor(editorInstance);
}
// We need to destroy the editor instance and re-initialize it
// when the deps array changes
editorInstance.destroy();
// the deps array is used to re-initialize the editor instance
editorInstance = createEditor(mostRecentOptions);
setEditor(editorInstance);
return () => destroyUnusedEditor(editorInstance);
}, deps);
// 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;
}
if (options.immediatelyRender && transactionNumber === 0) {
return 0;
}
return transactionNumber + 1;
}
});
return editor;
}
const EditorContext = createContext({
editor: null,
// src/Context.tsx
var EditorContext = createContext({
editor: null
});
const EditorConsumer = EditorContext.Consumer;
/**
* A hook to get the current editor instance.
*/
const useCurrentEditor = () => useContext(EditorContext);
/**
* 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);
if (!editor) {
return null;
}
return (React.createElement(EditorContext.Provider, { value: { editor } },
slotBefore,
React.createElement(EditorConsumer, null, ({ editor: currentEditor }) => (React.createElement(EditorContent, { editor: currentEditor }))),
children,
slotAfter));
var EditorConsumer = EditorContext.Consumer;
var useCurrentEditor = () => useContext(EditorContext);
function EditorProvider({
children,
slotAfter,
slotBefore,
...editorOptions
}) {
const editor = useEditor(editorOptions);
if (!editor) {
return null;
}
return /* @__PURE__ */ React2.createElement(EditorContext.Provider, { value: { editor } }, slotBefore, /* @__PURE__ */ React2.createElement(EditorConsumer, null, ({ editor: currentEditor }) => /* @__PURE__ */ React2.createElement(EditorContent, { editor: currentEditor })), children, slotAfter);
}
const BubbleMenu = (props) => {
const menuEl = useRef(document.createElement('div'));
const { editor: currentEditor } = useCurrentEditor();
useEffect(() => {
var _a;
menuEl.current.style.visibility = 'hidden';
menuEl.current.style.position = 'absolute';
if (((_a = props.editor) === null || _a === void 0 ? void 0 : _a.isDestroyed) || (currentEditor === null || currentEditor === void 0 ? void 0 : currentEditor.isDestroyed)) {
return;
// src/BubbleMenu.tsx
var BubbleMenu = (props) => {
const menuEl = useRef2(document.createElement("div"));
const { editor: currentEditor } = useCurrentEditor();
useEffect3(() => {
var _a;
menuEl.current.style.visibility = "hidden";
menuEl.current.style.position = "absolute";
if (((_a = props.editor) == null ? void 0 : _a.isDestroyed) || (currentEditor == null ? void 0 : currentEditor.isDestroyed)) {
return;
}
const {
pluginKey = "bubbleMenu",
editor,
updateDelay,
resizeDelay,
shouldShow = null
} = props;
const menuEditor = editor || currentEditor;
if (!menuEditor) {
console.warn("BubbleMenu component is not rendered inside of an editor component or does not have editor prop.");
return;
}
const plugin = BubbleMenuPlugin({
updateDelay,
resizeDelay,
editor: menuEditor,
element: menuEl.current,
pluginKey,
shouldShow,
options: props.options
});
menuEditor.registerPlugin(plugin);
return () => {
menuEditor.unregisterPlugin(pluginKey);
window.requestAnimationFrame(() => {
if (menuEl.current.parentNode) {
menuEl.current.parentNode.removeChild(menuEl.current);
}
const { pluginKey = 'bubbleMenu', editor, updateDelay, resizeDelay, shouldShow = null, } = props;
const menuEditor = editor || currentEditor;
if (!menuEditor) {
console.warn('BubbleMenu component is not rendered inside of an editor component or does not have editor prop.');
return;
}
const plugin = BubbleMenuPlugin({
updateDelay,
resizeDelay,
editor: menuEditor,
element: menuEl.current,
pluginKey,
shouldShow,
options: props.options,
});
menuEditor.registerPlugin(plugin);
return () => {
menuEditor.unregisterPlugin(pluginKey);
window.requestAnimationFrame(() => {
if (menuEl.current.parentNode) {
menuEl.current.parentNode.removeChild(menuEl.current);
}
});
};
}, [props.editor, currentEditor]);
const portal = createPortal((React.createElement("div", { className: props.className }, props.children)), menuEl.current);
return (React.createElement(React.Fragment, null, portal));
});
};
}, [props.editor, currentEditor]);
const portal = createPortal(
/* @__PURE__ */ React3.createElement("div", { className: props.className }, props.children),
menuEl.current
);
return /* @__PURE__ */ React3.createElement(React3.Fragment, null, portal);
};
const FloatingMenu = (props) => {
const menuEl = useRef(document.createElement('div'));
const { editor: currentEditor } = useCurrentEditor();
useEffect(() => {
var _a;
menuEl.current.style.visibility = 'hidden';
menuEl.current.style.position = 'absolute';
if (((_a = props.editor) === null || _a === void 0 ? void 0 : _a.isDestroyed) || (currentEditor === null || currentEditor === void 0 ? void 0 : currentEditor.isDestroyed)) {
return;
// src/FloatingMenu.tsx
import { FloatingMenuPlugin } from "@tiptap/extension-floating-menu";
import React4, {
useEffect as useEffect4,
useRef as useRef3
} from "react";
import { createPortal as createPortal2 } from "react-dom";
var FloatingMenu = (props) => {
const menuEl = useRef3(document.createElement("div"));
const { editor: currentEditor } = useCurrentEditor();
useEffect4(() => {
var _a;
menuEl.current.style.visibility = "hidden";
menuEl.current.style.position = "absolute";
if (((_a = props.editor) == null ? void 0 : _a.isDestroyed) || (currentEditor == null ? void 0 : currentEditor.isDestroyed)) {
return;
}
const {
pluginKey = "floatingMenu",
editor,
options,
shouldShow = null
} = props;
const menuEditor = editor || currentEditor;
if (!menuEditor) {
console.warn("FloatingMenu component is not rendered inside of an editor component or does not have editor prop.");
return;
}
const plugin = FloatingMenuPlugin({
pluginKey,
editor: menuEditor,
element: menuEl.current,
options,
shouldShow
});
menuEditor.registerPlugin(plugin);
return () => {
menuEditor.unregisterPlugin(pluginKey);
window.requestAnimationFrame(() => {
if (menuEl.current.parentNode) {
menuEl.current.parentNode.removeChild(menuEl.current);
}
const { pluginKey = 'floatingMenu', editor, options, shouldShow = null, } = props;
const menuEditor = editor || currentEditor;
if (!menuEditor) {
console.warn('FloatingMenu component is not rendered inside of an editor component or does not have editor prop.');
return;
}
const plugin = FloatingMenuPlugin({
pluginKey,
editor: menuEditor,
element: menuEl.current,
options,
shouldShow,
});
menuEditor.registerPlugin(plugin);
return () => {
menuEditor.unregisterPlugin(pluginKey);
window.requestAnimationFrame(() => {
if (menuEl.current.parentNode) {
menuEl.current.parentNode.removeChild(menuEl.current);
}
});
};
}, [
props.editor,
currentEditor,
]);
const portal = createPortal((React.createElement("div", { className: props.className }, props.children)), menuEl.current);
return (React.createElement(React.Fragment, null, portal));
});
};
}, [
props.editor,
currentEditor
]);
const portal = createPortal2(
/* @__PURE__ */ React4.createElement("div", { className: props.className }, props.children),
menuEl.current
);
return /* @__PURE__ */ React4.createElement(React4.Fragment, null, portal);
};
const ReactNodeViewContext = createContext({
onDragStart: undefined,
// src/NodeViewContent.tsx
import React5 from "react";
// src/useReactNodeView.ts
import { createContext as createContext2, useContext as useContext2 } from "react";
var ReactNodeViewContext = createContext2({
onDragStart: void 0
});
const useReactNodeView = () => useContext(ReactNodeViewContext);
var useReactNodeView = () => useContext2(ReactNodeViewContext);
const NodeViewContent = props => {
const Tag = props.as || 'div';
const { nodeViewContentRef } = useReactNodeView();
return (React.createElement(Tag, { ...props, ref: nodeViewContentRef, "data-node-view-content": "", style: {
whiteSpace: 'pre-wrap',
...props.style,
} }));
// src/NodeViewContent.tsx
var NodeViewContent = (props) => {
const Tag = props.as || "div";
const { nodeViewContentRef } = useReactNodeView();
return (
// @ts-ignore
/* @__PURE__ */ React5.createElement(
Tag,
{
...props,
ref: nodeViewContentRef,
"data-node-view-content": "",
style: {
whiteSpace: "pre-wrap",
...props.style
}
}
)
);
};
const NodeViewWrapper = React.forwardRef((props, ref) => {
const { onDragStart } = useReactNodeView();
const Tag = props.as || 'div';
return (React.createElement(Tag, { ...props, ref: ref, "data-node-view-wrapper": "", onDragStart: onDragStart, style: {
whiteSpace: 'normal',
...props.style,
} }));
// src/NodeViewWrapper.tsx
import React6 from "react";
var NodeViewWrapper = React6.forwardRef((props, ref) => {
const { onDragStart } = useReactNodeView();
const Tag = props.as || "div";
return (
// @ts-ignore
/* @__PURE__ */ React6.createElement(
Tag,
{
...props,
ref,
"data-node-view-wrapper": "",
onDragStart,
style: {
whiteSpace: "normal",
...props.style
}
}
)
);
});
/**
* Check if a component is a class component.
* @param Component
* @returns {boolean}
*/
// src/ReactNodeViewRenderer.tsx
import {
NodeView
} from "@tiptap/core";
import React8 from "react";
// src/ReactRenderer.tsx
import React7 from "react";
import { flushSync } from "react-dom";
function isClassComponent(Component) {
return !!(typeof Component === 'function'
&& Component.prototype
&& Component.prototype.isReactComponent);
return !!(typeof Component === "function" && Component.prototype && Component.prototype.isReactComponent);
}
/**
* Check if a component is a forward ref component.
* @param Component
* @returns {boolean}
*/
function isForwardRefComponent(Component) {
var _a;
return !!(typeof Component === 'object'
&& ((_a = Component.$$typeof) === null || _a === void 0 ? void 0 : _a.toString()) === 'Symbol(react.forward_ref)');
var _a;
return !!(typeof Component === "object" && ((_a = Component.$$typeof) == null ? void 0 : _a.toString()) === "Symbol(react.forward_ref)");
}
/**
* The ReactRenderer class. It's responsible for rendering React components inside the editor.
* @example
* new ReactRenderer(MyComponent, {
* editor,
* props: {
* foo: 'bar',
* },
* as: 'span',
* })
*/
class ReactRenderer {
constructor(component, { editor, props = {}, as = 'div', className = '', attrs, }) {
this.ref = null;
this.id = Math.floor(Math.random() * 0xFFFFFFFF).toString();
this.component = component;
this.editor = editor;
this.props = props;
this.element = document.createElement(as);
this.element.classList.add('react-renderer');
if (className) {
this.element.classList.add(...className.split(' '));
}
if (attrs) {
Object.keys(attrs).forEach(key => {
this.element.setAttribute(key, attrs[key]);
});
}
this.render();
var ReactRenderer = class {
constructor(component, {
editor,
props = {},
as = "div",
className = "",
attrs
}) {
this.ref = null;
this.id = Math.floor(Math.random() * 4294967295).toString();
this.component = component;
this.editor = editor;
this.props = props;
this.element = document.createElement(as);
this.element.classList.add("react-renderer");
if (className) {
this.element.classList.add(...className.split(" "));
}
render() {
var _a, _b;
const Component = this.component;
const props = this.props;
if (isClassComponent(Component) || isForwardRefComponent(Component)) {
props.ref = (ref) => {
this.ref = ref;
};
}
this.reactElement = React.createElement(Component, { ...props });
(_b = (_a = this.editor) === null || _a === void 0 ? void 0 : _a.contentComponent) === null || _b === void 0 ? void 0 : _b.setRenderer(this.id, this);
if (attrs) {
Object.keys(attrs).forEach((key) => {
this.element.setAttribute(key, attrs[key]);
});
}
updateProps(props = {}) {
this.props = {
...this.props,
...props,
};
if (this.editor.isInitialized) {
flushSync(() => {
this.render();
});
} else {
this.render();
}
destroy() {
var _a, _b;
(_b = (_a = this.editor) === null || _a === void 0 ? void 0 : _a.contentComponent) === null || _b === void 0 ? void 0 : _b.removeRenderer(this.id);
}
render() {
var _a;
const Component = this.component;
const props = this.props;
const editor = this.editor;
if (isClassComponent(Component) || isForwardRefComponent(Component)) {
props.ref = (ref) => {
this.ref = ref;
};
}
}
this.reactElement = React7.createElement(Component, props);
(_a = editor == null ? void 0 : editor.contentComponent) == null ? void 0 : _a.setRenderer(this.id, this);
}
updateProps(props = {}) {
this.props = {
...this.props,
...props
};
this.render();
}
destroy() {
var _a;
const editor = this.editor;
(_a = editor == null ? void 0 : editor.contentComponent) == null ? void 0 : _a.removeRenderer(this.id);
}
};
class ReactNodeView extends NodeView {
mount() {
const props = {
editor: this.editor,
node: this.node,
decorations: this.decorations,
selected: false,
extension: this.extension,
getPos: () => this.getPos(),
updateAttributes: (attributes = {}) => this.updateAttributes(attributes),
deleteNode: () => this.deleteNode(),
};
if (!this.component.displayName) {
const capitalizeFirstChar = (string) => {
return string.charAt(0).toUpperCase() + string.substring(1);
};
this.component.displayName = capitalizeFirstChar(this.extension.name);
}
const ReactNodeViewProvider = componentProps => {
const Component = this.component;
const onDragStart = this.onDragStart.bind(this);
const nodeViewContentRef = element => {
if (element && this.contentDOMElement && element.firstChild !== this.contentDOMElement) {
element.appendChild(this.contentDOMElement);
}
};
return (React.createElement(React.Fragment, null,
React.createElement(ReactNodeViewContext.Provider, { value: { onDragStart, nodeViewContentRef } },
React.createElement(Component, { ...componentProps }))));
};
ReactNodeViewProvider.displayName = 'ReactNodeView';
if (this.node.isLeaf) {
this.contentDOMElement = null;
}
else if (this.options.contentDOMElementTag) {
this.contentDOMElement = document.createElement(this.options.contentDOMElementTag);
}
else {
this.contentDOMElement = document.createElement(this.node.isInline ? 'span' : 'div');
}
if (this.contentDOMElement) {
// For some reason the whiteSpace prop is not inherited properly in Chrome and Safari
// With this fix it seems to work fine
// See: https://github.com/ueberdosis/tiptap/issues/1197
this.contentDOMElement.style.whiteSpace = 'inherit';
}
let as = this.node.isInline ? 'span' : 'div';
if (this.options.as) {
as = this.options.as;
}
const { className = '' } = this.options;
this.handleSelectionUpdate = this.handleSelectionUpdate.bind(this);
this.editor.on('selectionUpdate', this.handleSelectionUpdate);
this.renderer = new ReactRenderer(ReactNodeViewProvider, {
editor: this.editor,
props,
as,
className: `node-${this.node.type.name} ${className}`.trim(),
attrs: this.options.attrs,
});
// src/ReactNodeViewRenderer.tsx
var ReactNodeView = class extends NodeView {
mount() {
const props = {
editor: this.editor,
node: this.node,
decorations: this.decorations,
selected: false,
extension: this.extension,
getPos: () => this.getPos(),
updateAttributes: (attributes = {}) => this.updateAttributes(attributes),
deleteNode: () => this.deleteNode()
};
if (!this.component.displayName) {
const capitalizeFirstChar = (string) => {
return string.charAt(0).toUpperCase() + string.substring(1);
};
this.component.displayName = capitalizeFirstChar(this.extension.name);
}
get dom() {
var _a;
if (this.renderer.element.firstElementChild
&& !((_a = this.renderer.element.firstElementChild) === null || _a === void 0 ? void 0 : _a.hasAttribute('data-node-view-wrapper'))) {
throw Error('Please use the NodeViewWrapper component for your node view.');
}
return this.renderer.element;
const onDragStart = this.onDragStart.bind(this);
const nodeViewContentRef = (element) => {
if (element && this.contentDOMElement && element.firstChild !== this.contentDOMElement) {
element.appendChild(this.contentDOMElement);
}
};
const context = { onDragStart, nodeViewContentRef };
const Component = this.component;
const ReactNodeViewProvider = React8.memo((componentProps) => {
return /* @__PURE__ */ React8.createElement(ReactNodeViewContext.Provider, { value: context }, React8.createElement(Component, componentProps));
});
ReactNodeViewProvider.displayName = "ReactNodeView";
if (this.node.isLeaf) {
this.contentDOMElement = null;
} else if (this.options.contentDOMElementTag) {
this.contentDOMElement = document.createElement(this.options.contentDOMElementTag);
} else {
this.contentDOMElement = document.createElement(this.node.isInline ? "span" : "div");
}
get contentDOM() {
if (this.node.isLeaf) {
return null;
}
return this.contentDOMElement;
if (this.contentDOMElement) {
this.contentDOMElement.style.whiteSpace = "inherit";
}
handleSelectionUpdate() {
const { from, to } = this.editor.state.selection;
if (from <= this.getPos() && to >= this.getPos() + this.node.nodeSize) {
if (this.renderer.props.selected) {
return;
}
this.selectNode();
}
else {
if (!this.renderer.props.selected) {
return;
}
this.deselectNode();
}
let as = this.node.isInline ? "span" : "div";
if (this.options.as) {
as = this.options.as;
}
update(node, decorations) {
const updateProps = (props) => {
this.renderer.updateProps(props);
};
if (node.type !== this.node.type) {
return false;
}
if (typeof this.options.update === 'function') {
const oldNode = this.node;
const oldDecorations = this.decorations;
this.node = node;
this.decorations = decorations;
return this.options.update({
oldNode,
oldDecorations,
newNode: node,
newDecorations: decorations,
updateProps: () => updateProps({ node, decorations }),
});
}
if (node === this.node && this.decorations === decorations) {
return true;
}
this.node = node;
this.decorations = decorations;
updateProps({ node, decorations });
return true;
const { className = "" } = this.options;
this.handleSelectionUpdate = this.handleSelectionUpdate.bind(this);
this.editor.on("selectionUpdate", this.handleSelectionUpdate);
this.renderer = new ReactRenderer(ReactNodeViewProvider, {
editor: this.editor,
props,
as,
className: `node-${this.node.type.name} ${className}`.trim(),
attrs: this.options.attrs
});
}
get dom() {
var _a;
if (this.renderer.element.firstElementChild && !((_a = this.renderer.element.firstElementChild) == null ? void 0 : _a.hasAttribute("data-node-view-wrapper"))) {
throw Error("Please use the NodeViewWrapper component for your node view.");
}
selectNode() {
this.renderer.updateProps({
selected: true,
});
this.renderer.element.classList.add('ProseMirror-selectednode');
return this.renderer.element;
}
get contentDOM() {
if (this.node.isLeaf) {
return null;
}
deselectNode() {
this.renderer.updateProps({
selected: false,
});
this.renderer.element.classList.remove('ProseMirror-selectednode');
return this.contentDOMElement;
}
handleSelectionUpdate() {
const { from, to } = this.editor.state.selection;
if (from <= this.getPos() && to >= this.getPos() + this.node.nodeSize) {
if (this.renderer.props.selected) {
return;
}
this.selectNode();
} else {
if (!this.renderer.props.selected) {
return;
}
this.deselectNode();
}
destroy() {
this.renderer.destroy();
this.editor.off('selectionUpdate', this.handleSelectionUpdate);
this.contentDOMElement = null;
}
update(node, decorations) {
const updateProps = (props) => {
this.renderer.updateProps(props);
};
if (node.type !== this.node.type) {
return false;
}
}
if (typeof this.options.update === "function") {
const oldNode = this.node;
const oldDecorations = this.decorations;
this.node = node;
this.decorations = decorations;
return this.options.update({
oldNode,
oldDecorations,
newNode: node,
newDecorations: decorations,
updateProps: () => updateProps({ node, decorations })
});
}
if (node === this.node && this.decorations === decorations) {
return true;
}
this.node = node;
this.decorations = decorations;
updateProps({ node, decorations });
return true;
}
selectNode() {
this.renderer.updateProps({
selected: true
});
this.renderer.element.classList.add("ProseMirror-selectednode");
}
deselectNode() {
this.renderer.updateProps({
selected: false
});
this.renderer.element.classList.remove("ProseMirror-selectednode");
}
destroy() {
this.renderer.destroy();
this.editor.off("selectionUpdate", this.handleSelectionUpdate);
this.contentDOMElement = null;
}
};
function ReactNodeViewRenderer(component, options) {
return (props) => {
// try to get the parent component
// this is important for vue devtools to show the component hierarchy correctly
// maybe it’s `undefined` because <editor-content> isn’t rendered yet
if (!props.editor.contentComponent) {
return {};
}
return new ReactNodeView(component, props, options);
};
return (props) => {
if (!props.editor.contentComponent) {
return {};
}
return new ReactNodeView(component, props, options);
};
}
export { BubbleMenu, Editor, EditorConsumer, EditorContent, EditorContext, EditorProvider, FloatingMenu, NodeViewContent, NodeViewWrapper, PureEditorContent, ReactNodeViewContext, ReactNodeViewRenderer, ReactRenderer, useCurrentEditor, useEditor, useEditorState, useReactNodeView };
//# sourceMappingURL=index.js.map
// src/index.ts
export * from "@tiptap/core";
export {
BubbleMenu,
EditorConsumer,
EditorContent,
EditorContext,
EditorProvider,
FloatingMenu,
NodeViewContent,
NodeViewWrapper,
PureEditorContent,
ReactNodeViewContext,
ReactNodeViewRenderer,
ReactRenderer,
useCurrentEditor,
useEditor,
useEditorState,
useReactNodeView
};
//# sourceMappingURL=index.js.map
{
"name": "@tiptap/react",
"description": "React components for tiptap",
"version": "3.0.0-next.0",
"version": "3.0.0-next.1",
"homepage": "https://tiptap.dev",

@@ -17,3 +17,3 @@ "keywords": [

".": {
"types": "./dist/packages/react/src/index.d.ts",
"types": "./dist/index.d.ts",
"import": "./dist/index.js",

@@ -25,4 +25,3 @@ "require": "./dist/index.cjs"

"module": "dist/index.js",
"umd": "dist/index.umd.js",
"types": "dist/packages/react/src/index.d.ts",
"types": "dist/index.d.ts",
"type": "module",

@@ -34,4 +33,4 @@ "files": [

"dependencies": {
"@tiptap/extension-bubble-menu": "^3.0.0-next.0",
"@tiptap/extension-floating-menu": "^3.0.0-next.0",
"@tiptap/extension-bubble-menu": "^3.0.0-next.1",
"@tiptap/extension-floating-menu": "^3.0.0-next.1",
"@types/use-sync-external-store": "^0.0.6",

@@ -41,4 +40,4 @@ "use-sync-external-store": "^1.2.2"

"devDependencies": {
"@tiptap/core": "^3.0.0-next.0",
"@tiptap/pm": "^3.0.0-next.0",
"@tiptap/core": "^3.0.0-next.1",
"@tiptap/pm": "^3.0.0-next.1",
"@types/react": "^18.2.14",

@@ -50,4 +49,4 @@ "@types/react-dom": "^18.2.6",

"peerDependencies": {
"@tiptap/core": "^3.0.0-next.0",
"@tiptap/pm": "^3.0.0-next.0",
"@tiptap/core": "^3.0.0-next.1",
"@tiptap/pm": "^3.0.0-next.1",
"react": "^17.0.0 || ^18.0.0",

@@ -63,5 +62,4 @@ "react-dom": "^17.0.0 || ^18.0.0"

"scripts": {
"clean": "rm -rf dist",
"build": "npm run clean && rollup -c"
"build": "tsup"
}
}

@@ -1,14 +0,13 @@

import { Editor as CoreEditor } from '@tiptap/core'
import React from 'react'
import { Editor } from '@tiptap/core'
import { ReactPortal } from 'react'
import { EditorContentProps, EditorContentState } from './EditorContent.js'
import { ReactRenderer } from './ReactRenderer.js'
type ContentComponent = React.Component<EditorContentProps, EditorContentState> & {
export type EditorWithContentComponent = Editor & { contentComponent?: ContentComponent | null }
export type ContentComponent = {
setRenderer(id: string, renderer: ReactRenderer): void;
removeRenderer(id: string): void;
subscribe: (callback: () => void) => () => void;
getSnapshot: () => Record<string, ReactPortal>;
getServerSnapshot: () => Record<string, ReactPortal>;
}
export class Editor extends CoreEditor {
public contentComponent: ContentComponent | null = null
}
export * from './BubbleMenu.js'
export * from './Context.js'
export { Editor } from './Editor.js'
export * from './EditorContent.js'

@@ -5,0 +4,0 @@ export * from './FloatingMenu.js'

@@ -1,8 +0,12 @@

import { EditorOptions } from '@tiptap/core'
import { type EditorOptions, Editor } from '@tiptap/core'
import {
DependencyList, MutableRefObject,
useDebugValue, useEffect, useRef, useState,
DependencyList,
MutableRefObject,
useDebugValue,
useEffect,
useRef,
useState,
} from 'react'
import { useSyncExternalStore } from 'use-sync-external-store/shim'
import { Editor } from './Editor.js'
import { useEditorState } from './useEditorState.js'

@@ -34,53 +38,66 @@

/**
* Create a new editor instance. And attach event listeners.
* This class handles the creation, destruction, and re-creation of the editor instance.
*/
function createEditor(options: MutableRefObject<UseEditorOptions>): Editor {
const editor = new Editor(options.current)
class EditorInstanceManager {
/**
* The current editor instance.
*/
private editor: Editor | null = null
editor.on('beforeCreate', (...args) => options.current.onBeforeCreate?.(...args))
editor.on('blur', (...args) => options.current.onBlur?.(...args))
editor.on('create', (...args) => options.current.onCreate?.(...args))
editor.on('destroy', (...args) => options.current.onDestroy?.(...args))
editor.on('focus', (...args) => options.current.onFocus?.(...args))
editor.on('selectionUpdate', (...args) => options.current.onSelectionUpdate?.(...args))
editor.on('transaction', (...args) => options.current.onTransaction?.(...args))
editor.on('update', (...args) => options.current.onUpdate?.(...args))
editor.on('contentError', (...args) => options.current.onContentError?.(...args))
/**
* The most recent options to apply to the editor.
*/
private options: MutableRefObject<UseEditorOptions>
return editor
}
/**
* The subscriptions to notify when the editor instance
* has been created or destroyed.
*/
private subscriptions = new Set<() => void>()
/**
* 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 & { immediatelyRender: true },
deps?: DependencyList
): Editor;
/**
* A timeout to destroy the editor if it was not mounted within a time frame.
*/
private scheduledDestructionTimeout: ReturnType<typeof setTimeout> | undefined
/**
* 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;
/**
* Whether the editor has been mounted.
*/
private isComponentMounted = false
export function useEditor(
options: UseEditorOptions = {},
deps: DependencyList = [],
): Editor | null {
const mostRecentOptions = useRef(options)
const [editor, setEditor] = useState(() => {
if (options.immediatelyRender === undefined) {
/**
* The most recent dependencies array.
*/
private previousDeps: DependencyList | null = null
/**
* The unique instance ID. This is used to identify the editor instance. And will be re-generated for each new instance.
*/
public instanceId = ''
constructor(options: MutableRefObject<UseEditorOptions>) {
this.options = options
this.subscriptions = new Set<() => void>()
this.setEditor(this.getInitialEditor())
this.getEditor = this.getEditor.bind(this)
this.getServerSnapshot = this.getServerSnapshot.bind(this)
this.subscribe = this.subscribe.bind(this)
this.refreshEditorInstance = this.refreshEditorInstance.bind(this)
this.scheduleDestroy = this.scheduleDestroy.bind(this)
this.onRender = this.onRender.bind(this)
this.createEditor = this.createEditor.bind(this)
}
private setEditor(editor: Editor | null) {
this.editor = editor
this.instanceId = Math.random().toString(36).slice(2, 9)
// Notify all subscribers that the editor instance has been created
this.subscriptions.forEach(cb => cb())
}
private getInitialEditor() {
if (this.options.current.immediatelyRender === undefined) {
if (isSSR || isNext) {
// TODO in the next major release, we should throw an error here
if (isDev) {

@@ -91,3 +108,3 @@ /**

*/
console.warn(
throw new Error(
'Tiptap Error: SSR has been detected, please set `immediatelyRender` explicitly to `false` to avoid hydration mismatches.',

@@ -102,6 +119,6 @@ )

// Default to immediately rendering when client-side rendering
return createEditor(mostRecentOptions)
return this.createEditor()
}
if (options.immediatelyRender && isSSR && isDev) {
if (this.options.current.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.

@@ -113,57 +130,193 @@ throw new Error(

if (options.immediatelyRender) {
return createEditor(mostRecentOptions)
if (this.options.current.immediatelyRender) {
return this.createEditor()
}
return null
})
const mostRecentEditor = useRef<Editor | null>(editor)
}
mostRecentEditor.current = editor
/**
* Create a new editor instance. And attach event listeners.
*/
private createEditor(): Editor {
const optionsToApply: Partial<EditorOptions> = {
...this.options.current,
// Always call the most recent version of the callback function by default
onBeforeCreate: (...args) => this.options.current.onBeforeCreate?.(...args),
onBlur: (...args) => this.options.current.onBlur?.(...args),
onCreate: (...args) => this.options.current.onCreate?.(...args),
onDestroy: (...args) => this.options.current.onDestroy?.(...args),
onFocus: (...args) => this.options.current.onFocus?.(...args),
onSelectionUpdate: (...args) => this.options.current.onSelectionUpdate?.(...args),
onTransaction: (...args) => this.options.current.onTransaction?.(...args),
onUpdate: (...args) => this.options.current.onUpdate?.(...args),
onContentError: (...args) => this.options.current.onContentError?.(...args),
}
const editor = new Editor(optionsToApply)
useDebugValue(editor)
// no need to keep track of the event listeners, they will be removed when the editor is destroyed
// This effect will handle creating/updating the editor instance
useEffect(() => {
const destroyUnusedEditor = (editorInstance: Editor | null) => {
if (editorInstance) {
// We need to destroy the editor asynchronously to avoid memory leaks
// because the editor instance is still being used in the component.
return editor
}
setTimeout(() => {
// re-use the editor instance if it hasn't been replaced yet
// otherwise, asynchronously destroy the old editor instance
if (editorInstance !== mostRecentEditor.current && !editorInstance.isDestroyed) {
editorInstance.destroy()
}
})
}
/**
* Get the current editor instance.
*/
getEditor(): Editor | null {
return this.editor
}
/**
* Always disable the editor on the server-side.
*/
getServerSnapshot(): null {
return null
}
/**
* Subscribe to the editor instance's changes.
*/
subscribe(onStoreChange: () => void) {
this.subscriptions.add(onStoreChange)
return () => {
this.subscriptions.delete(onStoreChange)
}
}
let editorInstance = mostRecentEditor.current
/**
* On each render, we will create, update, or destroy the editor instance.
* @param deps The dependencies to watch for changes
* @returns A cleanup function
*/
onRender(deps: DependencyList) {
// The returned callback will run on each render
return () => {
this.isComponentMounted = true
// Cleanup any scheduled destructions, since we are currently rendering
clearTimeout(this.scheduledDestructionTimeout)
if (!editorInstance) {
editorInstance = createEditor(mostRecentOptions)
setEditor(editorInstance)
return () => destroyUnusedEditor(editorInstance)
if (this.editor && !this.editor.isDestroyed && deps.length === 0) {
// if the editor does exist & deps are empty, we don't need to re-initialize the editor
// we can fast-path to update the editor options on the existing instance
this.editor.setOptions(this.options.current)
} else {
// When the editor:
// - does not yet exist
// - is destroyed
// - the deps array changes
// We need to destroy the editor instance and re-initialize it
this.refreshEditorInstance(deps)
}
return () => {
this.isComponentMounted = false
this.scheduleDestroy()
}
}
}
if (!Array.isArray(deps) || deps.length === 0) {
// if the editor does exist & deps are empty, we don't need to re-initialize the editor
// we can fast-path to update the editor options on the existing instance
editorInstance.setOptions(options)
/**
* Recreate the editor instance if the dependencies have changed.
*/
private refreshEditorInstance(deps: DependencyList) {
if (this.editor && !this.editor.isDestroyed) {
// Editor instance already exists
if (this.previousDeps === null) {
// If lastDeps has not yet been initialized, reuse the current editor instance
this.previousDeps = deps
return
}
const depsAreEqual = this.previousDeps.length === deps.length
&& this.previousDeps.every((dep, index) => dep === deps[index])
return () => destroyUnusedEditor(editorInstance)
if (depsAreEqual) {
// deps exist and are equal, no need to recreate
return
}
}
// We need to destroy the editor instance and re-initialize it
// when the deps array changes
editorInstance.destroy()
if (this.editor && !this.editor.isDestroyed) {
// Destroy the editor instance if it exists
this.editor.destroy()
}
// the deps array is used to re-initialize the editor instance
editorInstance = createEditor(mostRecentOptions)
setEditor(editorInstance)
return () => destroyUnusedEditor(editorInstance)
}, deps)
this.setEditor(this.createEditor())
// Update the lastDeps to the current deps
this.previousDeps = deps
}
/**
* Schedule the destruction of the editor instance.
* This will only destroy the editor if it was not mounted on the next tick.
* This is to avoid destroying the editor instance when it's actually still mounted.
*/
private scheduleDestroy() {
const currentInstanceId = this.instanceId
const currentEditor = this.editor
// Wait a tick to see if the component is still mounted
this.scheduledDestructionTimeout = setTimeout(() => {
if (this.isComponentMounted && this.instanceId === currentInstanceId) {
// If still mounted on the next tick, with the same instanceId, do not destroy the editor
if (currentEditor) {
// just re-apply options as they might have changed
currentEditor.setOptions(this.options.current)
}
return
}
if (currentEditor && !currentEditor.isDestroyed) {
currentEditor.destroy()
if (this.instanceId === currentInstanceId) {
this.setEditor(null)
}
}
}, 0)
}
}
/**
* 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 & { 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 mostRecentOptions = useRef(options)
mostRecentOptions.current = options
const [instanceManager] = useState(() => new EditorInstanceManager(mostRecentOptions))
const editor = useSyncExternalStore(
instanceManager.subscribe,
instanceManager.getEditor,
instanceManager.getServerSnapshot,
)
useDebugValue(editor)
// This effect will handle creating/updating the editor instance
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(instanceManager.onRender(deps))
// The default behavior is to re-render on each transaction

@@ -170,0 +323,0 @@ // This is legacy behavior that will be removed in future versions

@@ -0,6 +1,5 @@

import type { Editor } from '@tiptap/core'
import { useDebugValue, useEffect, useState } from 'react'
import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector'
import type { Editor } from './Editor.js'
export type EditorStateSnapshot<TEditor extends Editor | null = Editor | null> = {

@@ -33,64 +32,79 @@ editor: TEditor;

*/
function makeEditorStateInstance<TEditor extends Editor | null = Editor | null>(initialEditor: TEditor) {
let transactionNumber = 0
let lastTransactionNumber = 0
let lastSnapshot: EditorStateSnapshot<TEditor> = { editor: initialEditor, transactionNumber: 0 }
let editor = initialEditor
const subscribers = new Set<() => void>()
class EditorStateManager<TEditor extends Editor | null = Editor | null> {
private transactionNumber = 0
const editorInstance = {
/**
* Get the current editor instance.
*/
getSnapshot(): EditorStateSnapshot<TEditor> {
if (transactionNumber === lastTransactionNumber) {
return lastSnapshot
private lastTransactionNumber = 0
private lastSnapshot: EditorStateSnapshot<TEditor>
private editor: TEditor
private subscribers = new Set<() => void>()
constructor(initialEditor: TEditor) {
this.editor = initialEditor
this.lastSnapshot = { editor: initialEditor, transactionNumber: 0 }
this.getSnapshot = this.getSnapshot.bind(this)
this.getServerSnapshot = this.getServerSnapshot.bind(this)
this.watch = this.watch.bind(this)
this.subscribe = this.subscribe.bind(this)
}
/**
* Get the current editor instance.
*/
getSnapshot(): EditorStateSnapshot<TEditor> {
if (this.transactionNumber === this.lastTransactionNumber) {
return this.lastSnapshot
}
this.lastTransactionNumber = this.transactionNumber
this.lastSnapshot = { editor: this.editor, transactionNumber: this.transactionNumber }
return this.lastSnapshot
}
/**
* Always disable the editor on the server-side.
*/
getServerSnapshot(): EditorStateSnapshot<null> {
return { editor: null, transactionNumber: 0 }
}
/**
* Subscribe to the editor instance's changes.
*/
subscribe(callback: () => void): () => void {
this.subscribers.add(callback)
return () => {
this.subscribers.delete(callback)
}
}
/**
* Watch the editor instance for changes.
*/
watch(nextEditor: Editor | null): undefined | (() => void) {
this.editor = nextEditor as TEditor
if (this.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 = () => {
this.transactionNumber += 1
this.subscribers.forEach(callback => callback())
}
lastTransactionNumber = transactionNumber
lastSnapshot = { editor, transactionNumber }
return lastSnapshot
},
/**
* Always disable the editor on the server-side.
*/
getServerSnapshot(): EditorStateSnapshot<null> {
return { editor: null, transactionNumber: 0 }
},
/**
* Subscribe to the editor instance's changes.
*/
subscribe(callback: () => void) {
subscribers.add(callback)
const currentEditor = this.editor
currentEditor.on('transaction', fn)
return () => {
subscribers.delete(callback)
currentEditor.off('transaction', fn)
}
},
/**
* Watch the editor instance for changes.
*/
watch(nextEditor: Editor | null) {
editor = nextEditor as TEditor
}
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 undefined
}
return editorInstance
}

@@ -108,3 +122,3 @@

): TSelectorResult | null {
const [editorInstance] = useState(() => makeEditorStateInstance(options.editor))
const [editorInstance] = useState(() => new EditorStateManager(options.editor))

@@ -122,3 +136,3 @@ // Using the `useSyncExternalStore` hook to sync the editor instance with the component state

return editorInstance.watch(options.editor)
}, [options.editor])
}, [options.editor, editorInstance])

@@ -125,0 +139,0 @@ useDebugValue(selectedState)

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

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

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc