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 2.6.6 to 2.7.0-pre.0

dist/packages/core/src/plugins/DropPlugin.d.ts

218

dist/index.js
import { BubbleMenuPlugin } from '@tiptap/extension-bubble-menu';
import React, { forwardRef, useState, useEffect, useDebugValue, useRef, createContext, useContext } from 'react';
import ReactDOM, { flushSync } from 'react-dom';
import { Editor, NodeView } from '@tiptap/core';
import { Editor, NodeView, getRenderedAttributes } from '@tiptap/core';
export * from '@tiptap/core';
import { FloatingMenuPlugin } from '@tiptap/extension-floating-menu';
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var shim = {exports: {}};

@@ -443,2 +447,76 @@

var react = function equal(a, b) {
if (a === b) return true;
if (a && b && typeof a == 'object' && typeof b == 'object') {
if (a.constructor !== b.constructor) return false;
var length, i, keys;
if (Array.isArray(a)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (!equal(a[i], b[i])) return false;
return true;
}
if ((a instanceof Map) && (b instanceof Map)) {
if (a.size !== b.size) return false;
for (i of a.entries())
if (!b.has(i[0])) return false;
for (i of a.entries())
if (!equal(i[1], b.get(i[0]))) return false;
return true;
}
if ((a instanceof Set) && (b instanceof Set)) {
if (a.size !== b.size) return false;
for (i of a.entries())
if (!b.has(i[0])) return false;
return true;
}
if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (a[i] !== b[i]) return false;
return true;
}
if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) return false;
for (i = length; i-- !== 0;)
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
for (i = length; i-- !== 0;) {
var key = keys[i];
if (key === '_owner' && a.$$typeof) {
// React-specific: avoid traversing React elements' _owner.
// _owner contains circular references
// and is not needed when comparing the actual elements (and not their owners)
continue;
}
if (!equal(a[key], b[key])) return false;
}
return true;
}
// true if both NaN, false otherwise
return a!==a && b!==b;
};
var deepEqual = /*@__PURE__*/getDefaultExportFromCjs(react);
var withSelector = {exports: {}};

@@ -715,9 +793,21 @@

}
/**
* This hook allows you to watch for changes on the editor instance.
* It will allow you to select a part of the editor state and re-render the component when it changes.
* @example
* ```tsx
* const editor = useEditor({...options})
* const { currentSelection } = useEditorState({
* editor,
* selector: snapshot => ({ currentSelection: snapshot.editor.state.selection }),
* })
*/
function useEditorState(options) {
const [editorInstance] = useState(() => new EditorStateManager(options.editor));
var _a;
const [editorStateManager] = useState(() => new EditorStateManager(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);
const selectedState = withSelectorExports.useSyncExternalStoreWithSelector(editorStateManager.subscribe, editorStateManager.getSnapshot, editorStateManager.getServerSnapshot, options.selector, (_a = options.equalityFn) !== null && _a !== void 0 ? _a : deepEqual);
useEffect(() => {
return editorInstance.watch(options.editor);
}, [options.editor, editorInstance]);
return editorStateManager.watch(options.editor);
}, [options.editor, editorStateManager]);
useDebugValue(selectedState);

@@ -816,2 +906,4 @@ return selectedState;

onContentError: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onContentError) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
onDrop: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onDrop) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
onPaste: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onPaste) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
};

@@ -1105,3 +1197,6 @@ const editor = new Editor(optionsToApply);

class ReactRenderer {
constructor(component, { editor, props = {}, as = 'div', className = '', attrs, }) {
/**
* Immediately creates element and renders the provided React component.
*/
constructor(component, { editor, props = {}, as = 'div', className = '', }) {
this.ref = null;

@@ -1117,7 +1212,2 @@ this.id = Math.floor(Math.random() * 0xFFFFFFFF).toString();

}
if (attrs) {
Object.keys(attrs).forEach(key => {
this.element.setAttribute(key, attrs[key]);
});
}
if (this.editor.isInitialized) {

@@ -1134,2 +1224,5 @@ // On first render, we need to flush the render synchronously

}
/**
* Render the React component.
*/
render() {

@@ -1141,2 +1234,3 @@ var _a;

if (isClassComponent(Component) || isForwardRefComponent(Component)) {
// @ts-ignore This is a hack to make the ref work
props.ref = (ref) => {

@@ -1149,2 +1243,5 @@ this.ref = ref;

}
/**
* Re-renders the React component with new props.
*/
updateProps(props = {}) {

@@ -1157,2 +1254,5 @@ this.props = {

}
/**
* Destroy the React component.
*/
destroy() {

@@ -1163,5 +1263,17 @@ var _a;

}
/**
* Update the attributes of the element that holds the React component.
*/
updateAttributes(attributes) {
Object.keys(attributes).forEach(key => {
this.element.setAttribute(key, attributes[key]);
});
}
}
class ReactNodeView extends NodeView {
/**
* Setup the React component.
* Called on initialization.
*/
mount() {

@@ -1172,4 +1284,7 @@ const props = {

decorations: this.decorations,
innerDecorations: this.innerDecorations,
view: this.view,
selected: false,
extension: this.extension,
HTMLAttributes: this.HTMLAttributes,
getPos: () => this.getPos(),

@@ -1209,2 +1324,3 @@ updateAttributes: (attributes = {}) => this.updateAttributes(attributes),

if (this.contentDOMElement) {
this.contentDOMElement.dataset.nodeViewContentReact = '';
// For some reason the whiteSpace prop is not inherited properly in Chrome and Safari

@@ -1227,5 +1343,9 @@ // With this fix it seems to work fine

className: `node-${this.node.type.name} ${className}`.trim(),
attrs: this.options.attrs,
});
this.updateElementAttributes();
}
/**
* Return the DOM element.
* This is the element that will be used to display the node view.
*/
get dom() {

@@ -1239,2 +1359,6 @@ var _a;

}
/**
* Return the content DOM element.
* This is the element that will be used to display the rich-text content of the node.
*/
get contentDOM() {

@@ -1246,5 +1370,13 @@ if (this.node.isLeaf) {

}
/**
* On editor selection update, check if the node is selected.
* If it is, call `selectNode`, otherwise call `deselectNode`.
*/
handleSelectionUpdate() {
const { from, to } = this.editor.state.selection;
if (from <= this.getPos() && to >= this.getPos() + this.node.nodeSize) {
const pos = this.getPos();
if (typeof pos !== 'number') {
return;
}
if (from <= pos && to >= pos + this.node.nodeSize) {
if (this.renderer.props.selected) {

@@ -1262,5 +1394,12 @@ return;

}
update(node, decorations) {
const updateProps = (props) => {
/**
* On update, update the React component.
* To prevent unnecessary updates, the `update` option can be used.
*/
update(node, decorations, innerDecorations) {
const rerenderComponent = (props) => {
this.renderer.updateProps(props);
if (typeof this.options.attrs === 'function') {
this.updateElementAttributes();
}
};

@@ -1273,4 +1412,6 @@ if (node.type !== this.node.type) {

const oldDecorations = this.decorations;
const oldInnerDecorations = this.innerDecorations;
this.node = node;
this.decorations = decorations;
this.innerDecorations = innerDecorations;
return this.options.update({

@@ -1281,6 +1422,10 @@ oldNode,

newDecorations: decorations,
updateProps: () => updateProps({ node, decorations }),
oldInnerDecorations,
innerDecorations,
updateProps: () => rerenderComponent({ node, decorations, innerDecorations }),
});
}
if (node === this.node && this.decorations === decorations) {
if (node === this.node
&& this.decorations === decorations
&& this.innerDecorations === innerDecorations) {
return true;

@@ -1290,5 +1435,10 @@ }

this.decorations = decorations;
updateProps({ node, decorations });
this.innerDecorations = innerDecorations;
rerenderComponent({ node, decorations, innerDecorations });
return true;
}
/**
* Select the node.
* Add the `selected` prop and the `ProseMirror-selectednode` class.
*/
selectNode() {

@@ -1300,2 +1450,6 @@ this.renderer.updateProps({

}
/**
* Deselect the node.
* Remove the `selected` prop and the `ProseMirror-selectednode` class.
*/
deselectNode() {

@@ -1307,2 +1461,5 @@ this.renderer.updateProps({

}
/**
* Destroy the React component instance.
*/
destroy() {

@@ -1313,5 +1470,26 @@ this.renderer.destroy();

}
/**
* Update the attributes of the top-level element that holds the React component.
* Applying the attributes defined in the `attrs` option.
*/
updateElementAttributes() {
if (this.options.attrs) {
let attrsObj = {};
if (typeof this.options.attrs === 'function') {
const extensionAttributes = this.editor.extensionManager.attributes;
const HTMLAttributes = getRenderedAttributes(this.node, extensionAttributes);
attrsObj = this.options.attrs({ node: this.node, HTMLAttributes });
}
else {
attrsObj = this.options.attrs;
}
this.renderer.updateAttributes(attrsObj);
}
}
}
/**
* Create a React node view renderer.
*/
function ReactNodeViewRenderer(component, options) {
return (props) => {
return props => {
// try to get the parent component

@@ -1327,3 +1505,3 @@ // this is important for vue devtools to show the component hierarchy correctly

export { BubbleMenu, EditorConsumer, EditorContent, EditorContext, EditorProvider, FloatingMenu, NodeViewContent, NodeViewWrapper, PureEditorContent, ReactNodeViewContext, ReactNodeViewRenderer, ReactRenderer, useCurrentEditor, useEditor, useEditorState, useReactNodeView };
export { BubbleMenu, EditorConsumer, EditorContent, EditorContext, EditorProvider, FloatingMenu, NodeViewContent, NodeViewWrapper, PureEditorContent, ReactNodeView, ReactNodeViewContext, ReactNodeViewRenderer, ReactRenderer, useCurrentEditor, useEditor, useEditorState, useReactNodeView };
//# sourceMappingURL=index.js.map

2627

dist/index.umd.js
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@tiptap/extension-bubble-menu'), require('react'), require('react-dom'), require('@tiptap/core'), require('@tiptap/extension-floating-menu')) :
typeof define === 'function' && define.amd ? define(['exports', '@tiptap/extension-bubble-menu', 'react', 'react-dom', '@tiptap/core', '@tiptap/extension-floating-menu'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@tiptap/react"] = {}, global.extensionBubbleMenu, global.React, global.ReactDOM, global.core, global.extensionFloatingMenu));
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@tiptap/extension-bubble-menu'), require('react'), require('react-dom'), require('@tiptap/core'), require('@tiptap/extension-floating-menu')) :
typeof define === 'function' && define.amd ? define(['exports', '@tiptap/extension-bubble-menu', 'react', 'react-dom', '@tiptap/core', '@tiptap/extension-floating-menu'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@tiptap/react"] = {}, global.extensionBubbleMenu, global.React, global.ReactDOM, global.core, global.extensionFloatingMenu));
})(this, (function (exports, extensionBubbleMenu, React, ReactDOM, core, extensionFloatingMenu) { 'use strict';
var shim = {exports: {}};
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var useSyncExternalStoreShim_production_min = {};
var shim = {exports: {}};
/**
* @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 useSyncExternalStoreShim_production_min = {};
var hasRequiredUseSyncExternalStoreShim_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.
*/
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 hasRequiredUseSyncExternalStoreShim_production_min;
var useSyncExternalStoreShim_development = {};
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;
}
/**
* @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 useSyncExternalStoreShim_development = {};
var hasRequiredUseSyncExternalStoreShim_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.
*/
function requireUseSyncExternalStoreShim_development () {
if (hasRequiredUseSyncExternalStoreShim_development) return useSyncExternalStoreShim_development;
hasRequiredUseSyncExternalStoreShim_development = 1;
var hasRequiredUseSyncExternalStoreShim_development;
if (process.env.NODE_ENV !== "production") {
(function() {
function requireUseSyncExternalStoreShim_development () {
if (hasRequiredUseSyncExternalStoreShim_development) return useSyncExternalStoreShim_development;
hasRequiredUseSyncExternalStoreShim_development = 1;
/* 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;
if (process.env.NODE_ENV !== "production") {
(function() {
var ReactSharedInternals = React$1.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
/* 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;
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];
}
var ReactSharedInternals = React$1.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
printWarning('error', format, args);
}
}
}
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];
}
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();
printWarning('error', format, args);
}
}
}
if (stack !== '') {
format += '%s';
args = args.concat([stack]);
} // eslint-disable-next-line react-internal/safe-string-coercion
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
var argsWithFormat = args.map(function (item) {
return String(item);
}); // Careful: RN currently depends on this prefix
Function.prototype.apply.call(console[level], console, argsWithFormat);
}
}
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
/**
* 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
;
}
Function.prototype.apply.call(console[level], console, argsWithFormat);
}
}
var objectIs = typeof Object.is === 'function' ? Object.is : is;
/**
* 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
;
}
// dispatch for CommonJS interop named imports.
var objectIs = typeof Object.is === 'function' ? Object.is : is;
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.
// dispatch for CommonJS interop named imports.
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;
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.
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.
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();
var value = getSnapshot();
if (!objectIs(value, cachedValue)) {
error('The result of getSnapshot should be cached to avoid an infinite loop');
{
if (!didWarnUncachedGetSnapshot) {
var cachedValue = getSnapshot();
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.
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.
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
});
}
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.
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.
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;
return subscribe(handleStoreChange);
}, [subscribe]);
useDebugValue(value);
return value;
}
try {
var nextValue = latestGetSnapshot();
return !objectIs(prevValue, nextValue);
} catch (error) {
return true;
}
}
function checkIfSnapshotChanged(inst) {
var latestGetSnapshot = inst.getSnapshot;
var prevValue = inst.value;
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();
}
try {
var nextValue = latestGetSnapshot();
return !objectIs(prevValue, nextValue);
} catch (error) {
return true;
}
}
var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');
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 isServerEnvironment = !canUseDOM;
var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');
var shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore;
var useSyncExternalStore$2 = React$1.useSyncExternalStore !== undefined ? React$1.useSyncExternalStore : shim;
var isServerEnvironment = !canUseDOM;
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 shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore;
var useSyncExternalStore$2 = React$1.useSyncExternalStore !== undefined ? React$1.useSyncExternalStore : shim;
if (process.env.NODE_ENV === 'production') {
shim.exports = requireUseSyncExternalStoreShim_production_min();
} else {
shim.exports = requireUseSyncExternalStoreShim_development();
}
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 shimExports = shim.exports;
if (process.env.NODE_ENV === 'production') {
shim.exports = requireUseSyncExternalStoreShim_production_min();
} else {
shim.exports = requireUseSyncExternalStoreShim_development();
}
const mergeRefs = (...refs) => {
return (node) => {
refs.forEach(ref => {
if (typeof ref === 'function') {
ref(node);
}
else if (ref) {
ref.current = node;
}
});
};
};
/**
* This component renders all of the editor's node views.
*/
const Portals = ({ contentComponent, }) => {
// For performance reasons, we render the node view portals on state changes only
const renderers = shimExports.useSyncExternalStore(contentComponent.subscribe, contentComponent.getSnapshot, contentComponent.getServerSnapshot);
// This allows us to directly render the portals without any additional wrapper
return (React.createElement(React.Fragment, null, Object.values(renderers)));
};
function getInstance() {
const subscribers = 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());
},
};
}
class PureEditorContent extends React.Component {
constructor(props) {
var _a;
super(props);
this.editorContentRef = React.createRef();
this.initialized = false;
this.state = {
hasContentComponentInitialized: Boolean((_a = props.editor) === null || _a === void 0 ? 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();
// Has the content component been initialized?
if (!this.state.hasContentComponentInitialized) {
// Subscribe to the content component
this.unsubscribeToContentComponent = editor.contentComponent.subscribe(() => {
this.setState(prevState => {
if (!prevState.hasContentComponentInitialized) {
return {
hasContentComponentInitialized: true,
};
}
return prevState;
});
// Unsubscribe to previous content component
if (this.unsubscribeToContentComponent) {
this.unsubscribeToContentComponent();
}
});
}
editor.createNodeViews();
this.initialized = true;
}
}
componentWillUnmount() {
const editor = this.props.editor;
if (!editor) {
return;
}
this.initialized = false;
if (!editor.isDestroyed) {
editor.view.setProps({
nodeViews: {},
});
}
if (this.unsubscribeToContentComponent) {
this.unsubscribeToContentComponent();
}
editor.contentComponent = null;
if (!editor.options.element.firstChild) {
return;
}
const newElement = document.createElement('div');
newElement.append(...editor.options.element.childNodes);
editor.setOptions({
element: newElement,
});
}
render() {
const { editor, innerRef, ...rest } = this.props;
return (React.createElement(React.Fragment, null,
React.createElement("div", { ref: mergeRefs(innerRef, this.editorContentRef), ...rest }),
(editor === null || editor === void 0 ? void 0 : editor.contentComponent) && React.createElement(Portals, { contentComponent: editor.contentComponent })));
}
}
// EditorContent should be re-created whenever the Editor instance changes
const EditorContentWithKey = React.forwardRef((props, ref) => {
const key = React.useMemo(() => {
return Math.floor(Math.random() * 0xffffffff).toString();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [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,
});
});
const EditorContent = React.memo(EditorContentWithKey);
var shimExports = shim.exports;
var withSelector = {exports: {}};
const mergeRefs = (...refs) => {
return (node) => {
refs.forEach(ref => {
if (typeof ref === 'function') {
ref(node);
}
else if (ref) {
ref.current = node;
}
});
};
};
/**
* This component renders all of the editor's node views.
*/
const Portals = ({ contentComponent, }) => {
// For performance reasons, we render the node view portals on state changes only
const renderers = shimExports.useSyncExternalStore(contentComponent.subscribe, contentComponent.getSnapshot, contentComponent.getServerSnapshot);
// This allows us to directly render the portals without any additional wrapper
return (React.createElement(React.Fragment, null, Object.values(renderers)));
};
function getInstance() {
const subscribers = 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());
},
};
}
class PureEditorContent extends React.Component {
constructor(props) {
var _a;
super(props);
this.editorContentRef = React.createRef();
this.initialized = false;
this.state = {
hasContentComponentInitialized: Boolean((_a = props.editor) === null || _a === void 0 ? 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();
// Has the content component been initialized?
if (!this.state.hasContentComponentInitialized) {
// Subscribe to the content component
this.unsubscribeToContentComponent = editor.contentComponent.subscribe(() => {
this.setState(prevState => {
if (!prevState.hasContentComponentInitialized) {
return {
hasContentComponentInitialized: true,
};
}
return prevState;
});
// Unsubscribe to previous content component
if (this.unsubscribeToContentComponent) {
this.unsubscribeToContentComponent();
}
});
}
editor.createNodeViews();
this.initialized = true;
}
}
componentWillUnmount() {
const editor = this.props.editor;
if (!editor) {
return;
}
this.initialized = false;
if (!editor.isDestroyed) {
editor.view.setProps({
nodeViews: {},
});
}
if (this.unsubscribeToContentComponent) {
this.unsubscribeToContentComponent();
}
editor.contentComponent = null;
if (!editor.options.element.firstChild) {
return;
}
const newElement = document.createElement('div');
newElement.append(...editor.options.element.childNodes);
editor.setOptions({
element: newElement,
});
}
render() {
const { editor, innerRef, ...rest } = this.props;
return (React.createElement(React.Fragment, null,
React.createElement("div", { ref: mergeRefs(innerRef, this.editorContentRef), ...rest }),
(editor === null || editor === void 0 ? void 0 : editor.contentComponent) && React.createElement(Portals, { contentComponent: editor.contentComponent })));
}
}
// EditorContent should be re-created whenever the Editor instance changes
const EditorContentWithKey = React.forwardRef((props, ref) => {
const key = React.useMemo(() => {
return Math.floor(Math.random() * 0xffffffff).toString();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [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,
});
});
const EditorContent = React.memo(EditorContentWithKey);
var withSelector_production_min = {};
var react = function equal(a, b) {
if (a === b) return true;
/**
* @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.
*/
if (a && b && typeof a == 'object' && typeof b == 'object') {
if (a.constructor !== b.constructor) return false;
var hasRequiredWithSelector_production_min;
var length, i, keys;
if (Array.isArray(a)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (!equal(a[i], b[i])) return false;
return true;
}
function requireWithSelector_production_min () {
if (hasRequiredWithSelector_production_min) return withSelector_production_min;
hasRequiredWithSelector_production_min = 1;
var h=React,n=shimExports;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 = {};
if ((a instanceof Map) && (b instanceof Map)) {
if (a.size !== b.size) return false;
for (i of a.entries())
if (!b.has(i[0])) return false;
for (i of a.entries())
if (!equal(i[1], b.get(i[0]))) return false;
return true;
}
/**
* @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.
*/
if ((a instanceof Set) && (b instanceof Set)) {
if (a.size !== b.size) return false;
for (i of a.entries())
if (!b.has(i[0])) return false;
return true;
}
var hasRequiredWithSelector_development;
if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (a[i] !== b[i]) return false;
return true;
}
function requireWithSelector_development () {
if (hasRequiredWithSelector_development) return withSelector_development;
hasRequiredWithSelector_development = 1;
if (process.env.NODE_ENV !== "production") {
(function() {
if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
/* 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 = shimExports;
keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) return false;
/**
* 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
;
}
for (i = length; i-- !== 0;)
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
var objectIs = typeof Object.is === 'function' ? Object.is : is;
for (i = length; i-- !== 0;) {
var key = keys[i];
var useSyncExternalStore = shim.useSyncExternalStore;
if (key === '_owner' && a.$$typeof) {
// React-specific: avoid traversing React elements' _owner.
// _owner contains circular references
// and is not needed when comparing the actual elements (and not their owners)
continue;
}
// for CommonJS interop.
if (!equal(a[key], b[key])) return false;
}
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.
return true;
}
function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {
// Use this to track the rendered snapshot.
var instRef = useRef(null);
var inst;
// true if both NaN, false otherwise
return a!==a && b!==b;
};
if (instRef.current === null) {
inst = {
hasValue: false,
value: null
};
instRef.current = inst;
} else {
inst = instRef.current;
}
var deepEqual = /*@__PURE__*/getDefaultExportFromCjs(react);
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 withSelector = {exports: {}};
var memoizedSelector = function (nextSnapshot) {
if (!hasMemo) {
// The first time the hook is called, there is no memoized result.
hasMemo = true;
memoizedSnapshot = nextSnapshot;
var withSelector_production_min = {};
var _nextSelection = selector(nextSnapshot);
/**
* @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.
*/
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;
var hasRequiredWithSelector_production_min;
if (isEqual(currentSelection, _nextSelection)) {
memoizedSelection = currentSelection;
return currentSelection;
}
}
}
function requireWithSelector_production_min () {
if (hasRequiredWithSelector_production_min) return withSelector_production_min;
hasRequiredWithSelector_production_min = 1;
var h=React,n=shimExports;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;
}
memoizedSelection = _nextSelection;
return _nextSelection;
} // We may be able to reuse the previous invocation's result.
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.
*/
// We may be able to reuse the previous invocation's result.
var prevSnapshot = memoizedSnapshot;
var prevSelection = memoizedSelection;
var hasRequiredWithSelector_development;
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.
function requireWithSelector_development () {
if (hasRequiredWithSelector_development) return withSelector_development;
hasRequiredWithSelector_development = 1;
if (process.env.NODE_ENV !== "production") {
(function() {
// 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.
/* 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 = shimExports;
// 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;
}
/**
* 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
;
}
memoizedSnapshot = nextSnapshot;
memoizedSelection = nextSelection;
return nextSelection;
}; // Assigning this to a constant so that Flow knows it can't change.
var objectIs = typeof Object.is === 'function' ? Object.is : is;
var useSyncExternalStore = shim.useSyncExternalStore;
// Assigning this to a constant so that Flow knows it can't change.
var maybeGetServerSnapshot = getServerSnapshot === undefined ? null : getServerSnapshot;
// for CommonJS interop.
var getSnapshotWithSelector = function () {
return memoizedSelector(getSnapshot());
};
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.
var getServerSnapshotWithSelector = maybeGetServerSnapshot === null ? undefined : function () {
return memoizedSelector(maybeGetServerSnapshot());
};
return [getSnapshotWithSelector, getServerSnapshotWithSelector];
}, [getSnapshot, getServerSnapshot, selector, isEqual]),
getSelection = _useMemo[0],
getServerSelection = _useMemo[1];
function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {
// Use this to track the rendered snapshot.
var instRef = useRef(null);
var inst;
var value = useSyncExternalStore(subscribe, getSelection, getServerSelection);
useEffect(function () {
inst.hasValue = true;
inst.value = value;
}, [value]);
useDebugValue(value);
return value;
}
if (instRef.current === null) {
inst = {
hasValue: false,
value: null
};
instRef.current = inst;
} else {
inst = instRef.current;
}
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;
}
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;
if (process.env.NODE_ENV === 'production') {
withSelector.exports = requireWithSelector_production_min();
} else {
withSelector.exports = requireWithSelector_development();
}
var memoizedSelector = function (nextSnapshot) {
if (!hasMemo) {
// The first time the hook is called, there is no memoized result.
hasMemo = true;
memoizedSnapshot = nextSnapshot;
var withSelectorExports = withSelector.exports;
var _nextSelection = selector(nextSnapshot);
/**
* 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.
*/
class EditorStateManager {
constructor(initialEditor) {
this.transactionNumber = 0;
this.lastTransactionNumber = 0;
this.subscribers = 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;
}
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);
};
}
/**
* Watch the editor instance for changes.
*/
watch(nextEditor) {
this.editor = nextEditor;
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());
};
const currentEditor = this.editor;
currentEditor.on('transaction', fn);
return () => {
currentEditor.off('transaction', fn);
};
}
return undefined;
}
}
function useEditorState(options) {
const [editorInstance] = React.useState(() => new EditorStateManager(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, editorInstance]);
React.useDebugValue(selectedState);
return selectedState;
}
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;
const isDev = process.env.NODE_ENV !== 'production';
const isSSR = typeof window === 'undefined';
const isNext = isSSR || Boolean(typeof window !== 'undefined' && window.next);
/**
* This class handles the creation, destruction, and re-creation of the editor instance.
*/
class EditorInstanceManager {
constructor(options) {
/**
* The current editor instance.
*/
this.editor = null;
/**
* The subscriptions to notify when the editor instance
* has been created or destroyed.
*/
this.subscriptions = 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 = new Set();
this.setEditor(this.getInitialEditor());
this.scheduleDestroy();
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);
// Notify all subscribers that the editor instance has been created
this.subscriptions.forEach(cb => cb());
}
getInitialEditor() {
if (this.options.current.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 this.createEditor();
}
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.
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 || _b === void 0 ? void 0 : _b.call(_a, ...args); },
onBlur: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onBlur) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
onCreate: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onCreate) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
onDestroy: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onDestroy) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
onFocus: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onFocus) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
onSelectionUpdate: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onSelectionUpdate) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
onTransaction: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onTransaction) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
onUpdate: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onUpdate) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
onContentError: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onContentError) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
};
const editor = new core.Editor(optionsToApply);
// no need to keep track of the event listeners, they will be removed when the editor is destroyed
return editor;
}
/**
* 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) {
// 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 (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();
};
};
}
/**
* Recreate the editor instance if the dependencies have changed.
*/
refreshEditorInstance(deps) {
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]);
if (depsAreEqual) {
// deps exist and are equal, no need to recreate
return;
}
}
if (this.editor && !this.editor.isDestroyed) {
// Destroy the editor instance if it exists
this.editor.destroy();
}
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.
*/
scheduleDestroy() {
const currentInstanceId = this.instanceId;
const currentEditor = this.editor;
// Wait two ticks to see if the component is still mounted
this.scheduledDestructionTimeout = setTimeout(() => {
if (this.isComponentMounted && this.instanceId === currentInstanceId) {
// If still mounted on the following 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);
}
}
// This allows the effect to run again between ticks
// which may save us from having to re-create the editor
}, 1);
}
}
function useEditor(options = {}, deps = []) {
const mostRecentOptions = React.useRef(options);
mostRecentOptions.current = options;
const [instanceManager] = React.useState(() => new EditorInstanceManager(mostRecentOptions));
const editor = shimExports.useSyncExternalStore(instanceManager.subscribe, instanceManager.getEditor, instanceManager.getServerSnapshot);
React.useDebugValue(editor);
// This effect will handle creating/updating the editor instance
// eslint-disable-next-line react-hooks/exhaustive-deps
React.useEffect(instanceManager.onRender(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 (isEqual(currentSelection, _nextSelection)) {
memoizedSelection = currentSelection;
return currentSelection;
}
}
}
const EditorContext = React.createContext({
editor: null,
});
const EditorConsumer = EditorContext.Consumer;
/**
* A hook to get the current editor instance.
*/
const useCurrentEditor = () => React.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));
}
memoizedSelection = _nextSelection;
return _nextSelection;
} // We may be able to reuse the previous invocation's result.
const BubbleMenu = (props) => {
const [element, setElement] = React.useState(null);
const { editor: currentEditor } = useCurrentEditor();
React.useEffect(() => {
var _a;
if (!element) {
return;
}
if (((_a = props.editor) === null || _a === void 0 ? void 0 : _a.isDestroyed) || (currentEditor === null || currentEditor === void 0 ? void 0 : currentEditor.isDestroyed)) {
return;
}
const { pluginKey = 'bubbleMenu', editor, tippyOptions = {}, updateDelay, 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 = extensionBubbleMenu.BubbleMenuPlugin({
updateDelay,
editor: menuEditor,
element,
pluginKey,
shouldShow,
tippyOptions,
});
menuEditor.registerPlugin(plugin);
return () => menuEditor.unregisterPlugin(pluginKey);
}, [props.editor, currentEditor, element]);
return (React.createElement("div", { ref: setElement, className: props.className, style: { visibility: 'hidden' } }, props.children));
};
const FloatingMenu = (props) => {
const [element, setElement] = React.useState(null);
const { editor: currentEditor } = useCurrentEditor();
React.useEffect(() => {
var _a;
if (!element) {
return;
}
if (((_a = props.editor) === null || _a === void 0 ? void 0 : _a.isDestroyed) || (currentEditor === null || currentEditor === void 0 ? void 0 : currentEditor.isDestroyed)) {
return;
}
const { pluginKey = 'floatingMenu', editor, tippyOptions = {}, 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 = extensionFloatingMenu.FloatingMenuPlugin({
pluginKey,
editor: menuEditor,
element,
tippyOptions,
shouldShow,
});
menuEditor.registerPlugin(plugin);
return () => menuEditor.unregisterPlugin(pluginKey);
}, [
props.editor,
currentEditor,
element,
]);
return (React.createElement("div", { ref: setElement, className: props.className, style: { visibility: 'hidden' } }, props.children));
};
// We may be able to reuse the previous invocation's result.
var prevSnapshot = memoizedSnapshot;
var prevSelection = memoizedSelection;
const ReactNodeViewContext = React.createContext({
onDragStart: undefined,
});
const useReactNodeView = () => React.useContext(ReactNodeViewContext);
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.
const NodeViewContent = props => {
const Tag = props.as || 'div';
const { nodeViewContentRef } = useReactNodeView();
return (
// @ts-ignore
React.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 (
// @ts-ignore
React.createElement(Tag, { ...props, ref: ref, "data-node-view-wrapper": "", onDragStart: onDragStart, style: {
whiteSpace: 'normal',
...props.style,
} }));
});
// 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.
/**
* Check if a component is a class component.
* @param Component
* @returns {boolean}
*/
function isClassComponent(Component) {
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)');
}
/**
* 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]);
});
}
if (this.editor.isInitialized) {
// On first render, we need to flush the render synchronously
// Renders afterwards can be async, but this fixes a cursor positioning issue
ReactDOM.flushSync(() => {
this.render();
});
}
else {
this.render();
}
}
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 = React.createElement(Component, props);
(_a = editor === null || editor === void 0 ? void 0 : editor.contentComponent) === null || _a === void 0 ? 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 || editor === void 0 ? void 0 : editor.contentComponent) === null || _a === void 0 ? void 0 : _a.removeRenderer(this.id);
}
}
// 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;
}
class ReactNodeView extends core.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 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;
// For performance reasons, we memoize the provider component
// And all of the things it requires are declared outside of the component, so it doesn't need to re-render
const ReactNodeViewProvider = React.memo(componentProps => {
return (React.createElement(ReactNodeViewContext.Provider, { value: context }, 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,
});
}
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;
}
get contentDOM() {
if (this.node.isLeaf) {
return null;
}
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();
}
}
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);
};
}
memoizedSnapshot = nextSnapshot;
memoizedSelection = nextSelection;
return nextSelection;
}; // Assigning this to a constant so that Flow knows it can't change.
exports.BubbleMenu = BubbleMenu;
exports.EditorConsumer = EditorConsumer;
exports.EditorContent = EditorContent;
exports.EditorContext = EditorContext;
exports.EditorProvider = EditorProvider;
exports.FloatingMenu = FloatingMenu;
exports.NodeViewContent = NodeViewContent;
exports.NodeViewWrapper = NodeViewWrapper;
exports.PureEditorContent = PureEditorContent;
exports.ReactNodeViewContext = ReactNodeViewContext;
exports.ReactNodeViewRenderer = ReactNodeViewRenderer;
exports.ReactRenderer = ReactRenderer;
exports.useCurrentEditor = useCurrentEditor;
exports.useEditor = useEditor;
exports.useEditorState = useEditorState;
exports.useReactNodeView = useReactNodeView;
Object.keys(core).forEach(function (k) {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
enumerable: true,
get: function () { return core[k]; }
});
});
// 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.
*/
class EditorStateManager {
constructor(initialEditor) {
this.transactionNumber = 0;
this.lastTransactionNumber = 0;
this.subscribers = 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;
}
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);
};
}
/**
* Watch the editor instance for changes.
*/
watch(nextEditor) {
this.editor = nextEditor;
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());
};
const currentEditor = this.editor;
currentEditor.on('transaction', fn);
return () => {
currentEditor.off('transaction', fn);
};
}
return undefined;
}
}
/**
* This hook allows you to watch for changes on the editor instance.
* It will allow you to select a part of the editor state and re-render the component when it changes.
* @example
* ```tsx
* const editor = useEditor({...options})
* const { currentSelection } = useEditorState({
* editor,
* selector: snapshot => ({ currentSelection: snapshot.editor.state.selection }),
* })
*/
function useEditorState(options) {
var _a;
const [editorStateManager] = React.useState(() => new EditorStateManager(options.editor));
// Using the `useSyncExternalStore` hook to sync the editor instance with the component state
const selectedState = withSelectorExports.useSyncExternalStoreWithSelector(editorStateManager.subscribe, editorStateManager.getSnapshot, editorStateManager.getServerSnapshot, options.selector, (_a = options.equalityFn) !== null && _a !== void 0 ? _a : deepEqual);
React.useEffect(() => {
return editorStateManager.watch(options.editor);
}, [options.editor, editorStateManager]);
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);
/**
* This class handles the creation, destruction, and re-creation of the editor instance.
*/
class EditorInstanceManager {
constructor(options) {
/**
* The current editor instance.
*/
this.editor = null;
/**
* The subscriptions to notify when the editor instance
* has been created or destroyed.
*/
this.subscriptions = 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 = new Set();
this.setEditor(this.getInitialEditor());
this.scheduleDestroy();
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);
// Notify all subscribers that the editor instance has been created
this.subscriptions.forEach(cb => cb());
}
getInitialEditor() {
if (this.options.current.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 this.createEditor();
}
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.
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 || _b === void 0 ? void 0 : _b.call(_a, ...args); },
onBlur: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onBlur) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
onCreate: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onCreate) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
onDestroy: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onDestroy) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
onFocus: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onFocus) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
onSelectionUpdate: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onSelectionUpdate) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
onTransaction: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onTransaction) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
onUpdate: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onUpdate) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
onContentError: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onContentError) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
onDrop: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onDrop) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
onPaste: (...args) => { var _a, _b; return (_b = (_a = this.options.current).onPaste) === null || _b === void 0 ? void 0 : _b.call(_a, ...args); },
};
const editor = new core.Editor(optionsToApply);
// no need to keep track of the event listeners, they will be removed when the editor is destroyed
return editor;
}
/**
* 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) {
// 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 (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();
};
};
}
/**
* Recreate the editor instance if the dependencies have changed.
*/
refreshEditorInstance(deps) {
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]);
if (depsAreEqual) {
// deps exist and are equal, no need to recreate
return;
}
}
if (this.editor && !this.editor.isDestroyed) {
// Destroy the editor instance if it exists
this.editor.destroy();
}
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.
*/
scheduleDestroy() {
const currentInstanceId = this.instanceId;
const currentEditor = this.editor;
// Wait two ticks to see if the component is still mounted
this.scheduledDestructionTimeout = setTimeout(() => {
if (this.isComponentMounted && this.instanceId === currentInstanceId) {
// If still mounted on the following 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);
}
}
// This allows the effect to run again between ticks
// which may save us from having to re-create the editor
}, 1);
}
}
function useEditor(options = {}, deps = []) {
const mostRecentOptions = React.useRef(options);
mostRecentOptions.current = options;
const [instanceManager] = React.useState(() => new EditorInstanceManager(mostRecentOptions));
const editor = shimExports.useSyncExternalStore(instanceManager.subscribe, instanceManager.getEditor, instanceManager.getServerSnapshot);
React.useDebugValue(editor);
// This effect will handle creating/updating the editor instance
// eslint-disable-next-line react-hooks/exhaustive-deps
React.useEffect(instanceManager.onRender(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;
}
const EditorContext = React.createContext({
editor: null,
});
const EditorConsumer = EditorContext.Consumer;
/**
* A hook to get the current editor instance.
*/
const useCurrentEditor = () => React.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));
}
const BubbleMenu = (props) => {
const [element, setElement] = React.useState(null);
const { editor: currentEditor } = useCurrentEditor();
React.useEffect(() => {
var _a;
if (!element) {
return;
}
if (((_a = props.editor) === null || _a === void 0 ? void 0 : _a.isDestroyed) || (currentEditor === null || currentEditor === void 0 ? void 0 : currentEditor.isDestroyed)) {
return;
}
const { pluginKey = 'bubbleMenu', editor, tippyOptions = {}, updateDelay, 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 = extensionBubbleMenu.BubbleMenuPlugin({
updateDelay,
editor: menuEditor,
element,
pluginKey,
shouldShow,
tippyOptions,
});
menuEditor.registerPlugin(plugin);
return () => menuEditor.unregisterPlugin(pluginKey);
}, [props.editor, currentEditor, element]);
return (React.createElement("div", { ref: setElement, className: props.className, style: { visibility: 'hidden' } }, props.children));
};
const FloatingMenu = (props) => {
const [element, setElement] = React.useState(null);
const { editor: currentEditor } = useCurrentEditor();
React.useEffect(() => {
var _a;
if (!element) {
return;
}
if (((_a = props.editor) === null || _a === void 0 ? void 0 : _a.isDestroyed) || (currentEditor === null || currentEditor === void 0 ? void 0 : currentEditor.isDestroyed)) {
return;
}
const { pluginKey = 'floatingMenu', editor, tippyOptions = {}, 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 = extensionFloatingMenu.FloatingMenuPlugin({
pluginKey,
editor: menuEditor,
element,
tippyOptions,
shouldShow,
});
menuEditor.registerPlugin(plugin);
return () => menuEditor.unregisterPlugin(pluginKey);
}, [
props.editor,
currentEditor,
element,
]);
return (React.createElement("div", { ref: setElement, className: props.className, style: { visibility: 'hidden' } }, props.children));
};
const ReactNodeViewContext = React.createContext({
onDragStart: undefined,
});
const useReactNodeView = () => React.useContext(ReactNodeViewContext);
const NodeViewContent = props => {
const Tag = props.as || 'div';
const { nodeViewContentRef } = useReactNodeView();
return (
// @ts-ignore
React.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 (
// @ts-ignore
React.createElement(Tag, { ...props, ref: ref, "data-node-view-wrapper": "", onDragStart: onDragStart, style: {
whiteSpace: 'normal',
...props.style,
} }));
});
/**
* Check if a component is a class component.
* @param Component
* @returns {boolean}
*/
function isClassComponent(Component) {
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)');
}
/**
* 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 {
/**
* Immediately creates element and renders the provided React component.
*/
constructor(component, { editor, props = {}, as = 'div', className = '', }) {
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 (this.editor.isInitialized) {
// On first render, we need to flush the render synchronously
// Renders afterwards can be async, but this fixes a cursor positioning issue
ReactDOM.flushSync(() => {
this.render();
});
}
else {
this.render();
}
}
/**
* Render the React component.
*/
render() {
var _a;
const Component = this.component;
const props = this.props;
const editor = this.editor;
if (isClassComponent(Component) || isForwardRefComponent(Component)) {
// @ts-ignore This is a hack to make the ref work
props.ref = (ref) => {
this.ref = ref;
};
}
this.reactElement = React.createElement(Component, props);
(_a = editor === null || editor === void 0 ? void 0 : editor.contentComponent) === null || _a === void 0 ? void 0 : _a.setRenderer(this.id, this);
}
/**
* Re-renders the React component with new props.
*/
updateProps(props = {}) {
this.props = {
...this.props,
...props,
};
this.render();
}
/**
* Destroy the React component.
*/
destroy() {
var _a;
const editor = this.editor;
(_a = editor === null || editor === void 0 ? void 0 : editor.contentComponent) === null || _a === void 0 ? void 0 : _a.removeRenderer(this.id);
}
/**
* Update the attributes of the element that holds the React component.
*/
updateAttributes(attributes) {
Object.keys(attributes).forEach(key => {
this.element.setAttribute(key, attributes[key]);
});
}
}
class ReactNodeView extends core.NodeView {
/**
* Setup the React component.
* Called on initialization.
*/
mount() {
const props = {
editor: this.editor,
node: this.node,
decorations: this.decorations,
innerDecorations: this.innerDecorations,
view: this.view,
selected: false,
extension: this.extension,
HTMLAttributes: this.HTMLAttributes,
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 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;
// For performance reasons, we memoize the provider component
// And all of the things it requires are declared outside of the component, so it doesn't need to re-render
const ReactNodeViewProvider = React.memo(componentProps => {
return (React.createElement(ReactNodeViewContext.Provider, { value: context }, 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) {
this.contentDOMElement.dataset.nodeViewContentReact = '';
// 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(),
});
this.updateElementAttributes();
}
/**
* Return the DOM element.
* This is the element that will be used to display the node view.
*/
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;
}
/**
* Return the content DOM element.
* This is the element that will be used to display the rich-text content of the node.
*/
get contentDOM() {
if (this.node.isLeaf) {
return null;
}
return this.contentDOMElement;
}
/**
* On editor selection update, check if the node is selected.
* If it is, call `selectNode`, otherwise call `deselectNode`.
*/
handleSelectionUpdate() {
const { from, to } = this.editor.state.selection;
const pos = this.getPos();
if (typeof pos !== 'number') {
return;
}
if (from <= pos && to >= pos + this.node.nodeSize) {
if (this.renderer.props.selected) {
return;
}
this.selectNode();
}
else {
if (!this.renderer.props.selected) {
return;
}
this.deselectNode();
}
}
/**
* On update, update the React component.
* To prevent unnecessary updates, the `update` option can be used.
*/
update(node, decorations, innerDecorations) {
const rerenderComponent = (props) => {
this.renderer.updateProps(props);
if (typeof this.options.attrs === 'function') {
this.updateElementAttributes();
}
};
if (node.type !== this.node.type) {
return false;
}
if (typeof this.options.update === 'function') {
const oldNode = this.node;
const oldDecorations = this.decorations;
const oldInnerDecorations = this.innerDecorations;
this.node = node;
this.decorations = decorations;
this.innerDecorations = innerDecorations;
return this.options.update({
oldNode,
oldDecorations,
newNode: node,
newDecorations: decorations,
oldInnerDecorations,
innerDecorations,
updateProps: () => rerenderComponent({ node, decorations, innerDecorations }),
});
}
if (node === this.node
&& this.decorations === decorations
&& this.innerDecorations === innerDecorations) {
return true;
}
this.node = node;
this.decorations = decorations;
this.innerDecorations = innerDecorations;
rerenderComponent({ node, decorations, innerDecorations });
return true;
}
/**
* Select the node.
* Add the `selected` prop and the `ProseMirror-selectednode` class.
*/
selectNode() {
this.renderer.updateProps({
selected: true,
});
this.renderer.element.classList.add('ProseMirror-selectednode');
}
/**
* Deselect the node.
* Remove the `selected` prop and the `ProseMirror-selectednode` class.
*/
deselectNode() {
this.renderer.updateProps({
selected: false,
});
this.renderer.element.classList.remove('ProseMirror-selectednode');
}
/**
* Destroy the React component instance.
*/
destroy() {
this.renderer.destroy();
this.editor.off('selectionUpdate', this.handleSelectionUpdate);
this.contentDOMElement = null;
}
/**
* Update the attributes of the top-level element that holds the React component.
* Applying the attributes defined in the `attrs` option.
*/
updateElementAttributes() {
if (this.options.attrs) {
let attrsObj = {};
if (typeof this.options.attrs === 'function') {
const extensionAttributes = this.editor.extensionManager.attributes;
const HTMLAttributes = core.getRenderedAttributes(this.node, extensionAttributes);
attrsObj = this.options.attrs({ node: this.node, HTMLAttributes });
}
else {
attrsObj = this.options.attrs;
}
this.renderer.updateAttributes(attrsObj);
}
}
}
/**
* Create a React node view renderer.
*/
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);
};
}
exports.BubbleMenu = BubbleMenu;
exports.EditorConsumer = EditorConsumer;
exports.EditorContent = EditorContent;
exports.EditorContext = EditorContext;
exports.EditorProvider = EditorProvider;
exports.FloatingMenu = FloatingMenu;
exports.NodeViewContent = NodeViewContent;
exports.NodeViewWrapper = NodeViewWrapper;
exports.PureEditorContent = PureEditorContent;
exports.ReactNodeView = ReactNodeView;
exports.ReactNodeViewContext = ReactNodeViewContext;
exports.ReactNodeViewRenderer = ReactNodeViewRenderer;
exports.ReactRenderer = ReactRenderer;
exports.useCurrentEditor = useCurrentEditor;
exports.useEditor = useEditor;
exports.useEditorState = useEditorState;
exports.useReactNodeView = useReactNodeView;
Object.keys(core).forEach(function (k) {
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
enumerable: true,
get: function () { return core[k]; }
});
});
}));
//# sourceMappingURL=index.umd.js.map

@@ -14,2 +14,4 @@ export * from './CommandManager.js';

export * from './pasteRules/index.js';
export * from './plugins/DropPlugin.js';
export * from './plugins/PastePlugin.js';
export * from './Tracker.js';

@@ -16,0 +18,0 @@ export * from './types.js';

@@ -1,6 +0,4 @@

import { Node as ProseMirrorNode } from '@tiptap/pm/model';
import { NodeView as ProseMirrorNodeView } from '@tiptap/pm/view';
import { Editor as CoreEditor } from './Editor.js';
import { Node } from './Node.js';
import { DecorationWithType, NodeViewRendererOptions, NodeViewRendererProps } from './types.js';
import { NodeViewRendererOptions, NodeViewRendererProps } from './types.js';
/**

@@ -14,6 +12,9 @@ * Node views are used to customize the rendered DOM structure of a node.

options: Options;
extension: Node;
node: ProseMirrorNode;
decorations: DecorationWithType[];
getPos: any;
extension: NodeViewRendererProps['extension'];
node: NodeViewRendererProps['node'];
decorations: NodeViewRendererProps['decorations'];
innerDecorations: NodeViewRendererProps['innerDecorations'];
view: NodeViewRendererProps['view'];
getPos: NodeViewRendererProps['getPos'];
HTMLAttributes: NodeViewRendererProps['HTMLAttributes'];
isDragging: boolean;

@@ -26,2 +27,7 @@ constructor(component: Component, props: NodeViewRendererProps, options?: Partial<Options>);

stopEvent(event: Event): boolean;
/**
* Called when a DOM [mutation](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) or a selection change happens within the view.
* @return `false` if the editor should re-read the selection or re-parse the range around the mutation
* @return `true` if it can safely be ignored.
*/
ignoreMutation(mutation: MutationRecord | {

@@ -31,4 +37,10 @@ type: 'selection';

}): boolean;
updateAttributes(attributes: {}): void;
/**
* Update the attributes of the prosemirror node.
*/
updateAttributes(attributes: Record<string, any>): void;
/**
* Delete the node.
*/
deleteNode(): void;
}

@@ -1,4 +0,4 @@

import { Mark as ProseMirrorMark, Node as ProseMirrorNode, NodeType, ParseOptions } from '@tiptap/pm/model';
import { Mark as ProseMirrorMark, Node as ProseMirrorNode, NodeType, ParseOptions, Slice } from '@tiptap/pm/model';
import { EditorState, Transaction } from '@tiptap/pm/state';
import { Decoration, EditorProps, EditorView, NodeView } from '@tiptap/pm/view';
import { Decoration, EditorProps, EditorView, NodeView, NodeViewConstructor } from '@tiptap/pm/view';
import { Editor } from './Editor.js';

@@ -82,4 +82,21 @@ import { Extension } from './Extension.js';

enablePasteRules: EnableRules;
enableCoreExtensions: boolean;
/**
* Determines whether core extensions are enabled.
*
* If set to `false`, all core extensions will be disabled.
* To disable specific core extensions, provide an object where the keys are the extension names and the values are `false`.
* Extensions not listed in the object will remain enabled.
*
* @example
* // Disable all core extensions
* enabledCoreExtensions: false
*
* @example
* // Disable only the keymap core extension
* enabledCoreExtensions: { keymap: false }
*
* @default true
*/
enableCoreExtensions?: boolean | Partial<Record<'editable' | 'clipboardTextSerializer' | 'commands' | 'focusEvents' | 'keymap' | 'tabindex', false>>;
/**
* If `true`, the editor will check the content for errors on initialization.

@@ -104,2 +121,4 @@ * Emitting the `contentError` event if the content is invalid.

onDestroy: (props: EditorEvents['destroy']) => void;
onPaste: (e: ClipboardEvent, slice: Slice) => void;
onDrop: (e: DragEvent, slice: Slice, moved: boolean) => void;
}

@@ -175,15 +194,14 @@ export type HTMLContent = string;

}[keyof T];
export type Simplify<T> = {
[KeyType in keyof T]: T[KeyType];
} & {};
export type DecorationWithType = Decoration & {
type: NodeType;
};
export type NodeViewProps = {
editor: Editor;
node: ProseMirrorNode;
decorations: DecorationWithType[];
export type NodeViewProps = Simplify<Omit<NodeViewRendererProps, 'decorations'> & {
decorations: readonly DecorationWithType[];
selected: boolean;
extension: Node;
getPos: () => number;
updateAttributes: (attributes: Record<string, any>) => void;
deleteNode: () => void;
};
}>;
export interface NodeViewRendererOptions {

@@ -202,10 +220,12 @@ stopEvent: ((props: {

export type NodeViewRendererProps = {
node: Parameters<NodeViewConstructor>[0];
view: Parameters<NodeViewConstructor>[1];
getPos: () => number;
decorations: Parameters<NodeViewConstructor>[3];
innerDecorations: Parameters<NodeViewConstructor>[4];
editor: Editor;
node: ProseMirrorNode;
getPos: (() => number) | boolean;
extension: Node;
HTMLAttributes: Record<string, any>;
decorations: Decoration[];
extension: Node;
};
export type NodeViewRenderer = (props: NodeViewRendererProps) => NodeView | {};
export type NodeViewRenderer = (props: NodeViewRendererProps) => NodeView;
export type AnyCommands = Record<string, (...args: any[]) => Command>;

@@ -212,0 +232,0 @@ export type UnionCommands<T = Command> = UnionToIntersection<ValuesOf<Pick<Commands<T>, KeysWithTypeOf<Commands<T>, {}>>>>;

@@ -1,16 +0,95 @@

import { NodeViewRenderer, NodeViewRendererOptions } from '@tiptap/core';
import { Node as ProseMirrorNode } from '@tiptap/pm/model';
import { Decoration } from '@tiptap/pm/view';
import { Editor, NodeView, NodeViewProps, NodeViewRenderer, NodeViewRendererOptions } from '@tiptap/core';
import { Node, Node as ProseMirrorNode } from '@tiptap/pm/model';
import { Decoration, DecorationSource } from '@tiptap/pm/view';
import { ComponentType } from 'react';
import { ReactRenderer } from './ReactRenderer.js';
export interface ReactNodeViewRendererOptions extends NodeViewRendererOptions {
/**
* This function is called when the node view is updated.
* It allows you to compare the old node with the new node and decide if the component should update.
*/
update: ((props: {
oldNode: ProseMirrorNode;
oldDecorations: Decoration[];
oldDecorations: readonly Decoration[];
oldInnerDecorations: DecorationSource;
newNode: ProseMirrorNode;
newDecorations: Decoration[];
newDecorations: readonly Decoration[];
innerDecorations: DecorationSource;
updateProps: () => void;
}) => boolean) | null;
/**
* The tag name of the element wrapping the React component.
*/
as?: string;
/**
* The class name of the element wrapping the React component.
*/
className?: string;
attrs?: Record<string, string>;
/**
* Attributes that should be applied to the element wrapping the React component.
* If this is a function, it will be called each time the node view is updated.
* If this is an object, it will be applied once when the node view is mounted.
*/
attrs?: Record<string, string> | ((props: {
node: ProseMirrorNode;
HTMLAttributes: Record<string, any>;
}) => Record<string, string>);
}
export declare function ReactNodeViewRenderer(component: any, options?: Partial<ReactNodeViewRendererOptions>): NodeViewRenderer;
export declare class ReactNodeView<Component extends ComponentType<NodeViewProps> = ComponentType<NodeViewProps>, NodeEditor extends Editor = Editor, Options extends ReactNodeViewRendererOptions = ReactNodeViewRendererOptions> extends NodeView<Component, NodeEditor, Options> {
/**
* The renderer instance.
*/
renderer: ReactRenderer<unknown, NodeViewProps>;
/**
* The element that holds the rich-text content of the node.
*/
contentDOMElement: HTMLElement | null;
/**
* Setup the React component.
* Called on initialization.
*/
mount(): void;
/**
* Return the DOM element.
* This is the element that will be used to display the node view.
*/
get dom(): HTMLElement;
/**
* Return the content DOM element.
* This is the element that will be used to display the rich-text content of the node.
*/
get contentDOM(): HTMLElement | null;
/**
* On editor selection update, check if the node is selected.
* If it is, call `selectNode`, otherwise call `deselectNode`.
*/
handleSelectionUpdate(): void;
/**
* On update, update the React component.
* To prevent unnecessary updates, the `update` option can be used.
*/
update(node: Node, decorations: readonly Decoration[], innerDecorations: DecorationSource): boolean;
/**
* Select the node.
* Add the `selected` prop and the `ProseMirror-selectednode` class.
*/
selectNode(): void;
/**
* Deselect the node.
* Remove the `selected` prop and the `ProseMirror-selectednode` class.
*/
deselectNode(): void;
/**
* Destroy the React component instance.
*/
destroy(): void;
/**
* Update the attributes of the top-level element that holds the React component.
* Applying the attributes defined in the `attrs` option.
*/
updateElementAttributes(): void;
}
/**
* Create a React node view renderer.
*/
export declare function ReactNodeViewRenderer(component: ComponentType<NodeViewProps>, options?: Partial<ReactNodeViewRendererOptions>): NodeViewRenderer;

@@ -28,9 +28,2 @@ import { Editor } from '@tiptap/core';

className?: string;
/**
* The attributes of the element.
* @type {Record<string, string>}
* @default {}
* @example { 'data-foo': 'bar' }
*/
attrs?: Record<string, string>;
}

@@ -49,3 +42,3 @@ type ComponentType<R, P> = React.ComponentClass<P> | React.FunctionComponent<P> | React.ForwardRefExoticComponent<React.PropsWithoutRef<P> & React.RefAttributes<R>>;

*/
export declare class ReactRenderer<R = unknown, P = unknown> {
export declare class ReactRenderer<R = unknown, P extends Record<string, any> = {}> {
id: string;

@@ -55,10 +48,26 @@ editor: Editor;

element: Element;
props: Record<string, any>;
props: P;
reactElement: React.ReactNode;
ref: R | null;
constructor(component: ComponentType<R, P>, { editor, props, as, className, attrs, }: ReactRendererOptions);
/**
* Immediately creates element and renders the provided React component.
*/
constructor(component: ComponentType<R, P>, { editor, props, as, className, }: ReactRendererOptions);
/**
* Render the React component.
*/
render(): void;
/**
* Re-renders the React component with new props.
*/
updateProps(props?: Record<string, any>): void;
/**
* Destroy the React component.
*/
destroy(): void;
/**
* Update the attributes of the element that holds the React component.
*/
updateAttributes(attributes: Record<string, string>): void;
}
export {};

@@ -17,7 +17,29 @@ import type { Editor } from '@tiptap/core';

* A custom equality function to determine if the editor should re-render.
* @default `(a, b) => a === b`
* @default `deepEqual` from `fast-deep-equal`
*/
equalityFn?: (a: TSelectorResult, b: TSelectorResult | null) => boolean;
};
/**
* This hook allows you to watch for changes on the editor instance.
* It will allow you to select a part of the editor state and re-render the component when it changes.
* @example
* ```tsx
* const editor = useEditor({...options})
* const { currentSelection } = useEditorState({
* editor,
* selector: snapshot => ({ currentSelection: snapshot.editor.state.selection }),
* })
*/
export declare function useEditorState<TSelectorResult>(options: UseEditorStateOptions<TSelectorResult, Editor>): TSelectorResult;
/**
* This hook allows you to watch for changes on the editor instance.
* It will allow you to select a part of the editor state and re-render the component when it changes.
* @example
* ```tsx
* const editor = useEditor({...options})
* const { currentSelection } = useEditorState({
* editor,
* selector: snapshot => ({ currentSelection: snapshot.editor.state.selection }),
* })
*/
export declare function useEditorState<TSelectorResult>(options: UseEditorStateOptions<TSelectorResult, Editor | null>): TSelectorResult | null;
{
"name": "@tiptap/react",
"description": "React components for tiptap",
"version": "2.6.6",
"version": "2.7.0-pre.0",
"homepage": "https://tiptap.dev",

@@ -32,10 +32,11 @@ "keywords": [

"dependencies": {
"@tiptap/extension-bubble-menu": "^2.6.6",
"@tiptap/extension-floating-menu": "^2.6.6",
"@tiptap/extension-bubble-menu": "^2.7.0-pre.0",
"@tiptap/extension-floating-menu": "^2.7.0-pre.0",
"@types/use-sync-external-store": "^0.0.6",
"fast-deep-equal": "^3",
"use-sync-external-store": "^1.2.2"
},
"devDependencies": {
"@tiptap/core": "^2.6.6",
"@tiptap/pm": "^2.6.6",
"@tiptap/core": "^2.7.0-pre.0",
"@tiptap/pm": "^2.7.0-pre.0",
"@types/react": "^18.2.14",

@@ -47,4 +48,4 @@ "@types/react-dom": "^18.2.6",

"peerDependencies": {
"@tiptap/core": "^2.6.6",
"@tiptap/pm": "^2.6.6",
"@tiptap/core": "^2.7.0-pre.0",
"@tiptap/pm": "^2.7.0-pre.0",
"react": "^17.0.0 || ^18.0.0",

@@ -51,0 +52,0 @@ "react-dom": "^17.0.0 || ^18.0.0"

@@ -152,2 +152,4 @@ import { type EditorOptions, Editor } from '@tiptap/core'

onContentError: (...args) => this.options.current.onContentError?.(...args),
onDrop: (...args) => this.options.current.onDrop?.(...args),
onPaste: (...args) => this.options.current.onPaste?.(...args),
}

@@ -154,0 +156,0 @@ const editor = new Editor(optionsToApply)

import type { Editor } from '@tiptap/core'
import deepEqual from 'fast-deep-equal/es6/react'
import { useDebugValue, useEffect, useState } from 'react'

@@ -9,2 +10,3 @@ import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector'

};
export type UseEditorStateOptions<

@@ -24,3 +26,3 @@ TSelectorResult,

* A custom equality function to determine if the editor should re-render.
* @default `(a, b) => a === b`
* @default `deepEqual` from `fast-deep-equal`
*/

@@ -113,5 +115,27 @@ equalityFn?: (a: TSelectorResult, b: TSelectorResult | null) => boolean;

/**
* This hook allows you to watch for changes on the editor instance.
* It will allow you to select a part of the editor state and re-render the component when it changes.
* @example
* ```tsx
* const editor = useEditor({...options})
* const { currentSelection } = useEditorState({
* editor,
* selector: snapshot => ({ currentSelection: snapshot.editor.state.selection }),
* })
*/
export function useEditorState<TSelectorResult>(
options: UseEditorStateOptions<TSelectorResult, Editor>
): TSelectorResult;
/**
* This hook allows you to watch for changes on the editor instance.
* It will allow you to select a part of the editor state and re-render the component when it changes.
* @example
* ```tsx
* const editor = useEditor({...options})
* const { currentSelection } = useEditorState({
* editor,
* selector: snapshot => ({ currentSelection: snapshot.editor.state.selection }),
* })
*/
export function useEditorState<TSelectorResult>(

@@ -121,19 +145,30 @@ options: UseEditorStateOptions<TSelectorResult, Editor | null>

/**
* This hook allows you to watch for changes on the editor instance.
* It will allow you to select a part of the editor state and re-render the component when it changes.
* @example
* ```tsx
* const editor = useEditor({...options})
* const { currentSelection } = useEditorState({
* editor,
* selector: snapshot => ({ currentSelection: snapshot.editor.state.selection }),
* })
*/
export function useEditorState<TSelectorResult>(
options: UseEditorStateOptions<TSelectorResult, Editor> | UseEditorStateOptions<TSelectorResult, Editor | null>,
): TSelectorResult | null {
const [editorInstance] = useState(() => new EditorStateManager(options.editor))
const [editorStateManager] = useState(() => new EditorStateManager(options.editor))
// Using the `useSyncExternalStore` hook to sync the editor instance with the component state
const selectedState = useSyncExternalStoreWithSelector(
editorInstance.subscribe,
editorInstance.getSnapshot,
editorInstance.getServerSnapshot,
editorStateManager.subscribe,
editorStateManager.getSnapshot,
editorStateManager.getServerSnapshot,
options.selector as UseEditorStateOptions<TSelectorResult, Editor | null>['selector'],
options.equalityFn,
options.equalityFn ?? deepEqual,
)
useEffect(() => {
return editorInstance.watch(options.editor)
}, [options.editor, editorInstance])
return editorStateManager.watch(options.editor)
}, [options.editor, editorStateManager])

@@ -140,0 +175,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

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