gdpr audit implemented, email log, vollmachten, pdf delete cancel data privacy and vollmachten, removed message no id card in engergy car, and other contracts that are not telecom contracts, added insert counter for engery

This commit is contained in:
2026-03-21 11:59:53 +01:00
parent 89cf92eaf5
commit f2876f877e
1491 changed files with 265550 additions and 1292 deletions
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025, Tiptap GmbH
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+18
View File
@@ -0,0 +1,18 @@
# @tiptap/react
[![Version](https://img.shields.io/npm/v/@tiptap/react.svg?label=version)](https://www.npmjs.com/package/@tiptap/react)
[![Downloads](https://img.shields.io/npm/dm/@tiptap/react.svg)](https://npmcharts.com/compare/tiptap?minimal=true)
[![License](https://img.shields.io/npm/l/@tiptap/react.svg)](https://www.npmjs.com/package/@tiptap/react)
[![Sponsor](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub)](https://github.com/sponsors/ueberdosis)
## Introduction
Tiptap is a headless wrapper around [ProseMirror](https://ProseMirror.net) a toolkit for building rich text WYSIWYG editors, which is already in use at many well-known companies such as _New York Times_, _The Guardian_ or _Atlassian_.
## Official Documentation
Documentation can be found on the [Tiptap website](https://tiptap.dev).
## License
Tiptap is open sourced software licensed under the [MIT license](https://github.com/ueberdosis/tiptap/blob/main/LICENSE.md).
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+534
View File
@@ -0,0 +1,534 @@
import * as react_jsx_runtime from 'react/jsx-runtime';
import { EditorOptions, Editor, MarkViewRendererOptions, MarkView, MarkViewProps, MarkViewRenderer, NodeViewProps, NodeViewRendererOptions, NodeView, NodeViewRendererProps, NodeViewRenderer } from '@tiptap/core';
export * from '@tiptap/core';
import * as React from 'react';
import React__default, { DependencyList, ReactNode, HTMLAttributes, HTMLProps, ForwardedRef, ComponentProps, ComponentClass, FunctionComponent, ForwardRefExoticComponent, PropsWithoutRef, RefAttributes, ComponentType as ComponentType$1 } from 'react';
import { Node } from '@tiptap/pm/model';
import { Decoration, DecorationSource } from '@tiptap/pm/view';
/**
* The options for the `useEditor` hook.
*/
type UseEditorOptions = Partial<EditorOptions> & {
/**
* Whether to render the editor on the first render.
* If client-side rendering, set this to `true`.
* If server-side rendering, set this to `false`.
* @default true
*/
immediatelyRender?: boolean;
/**
* Whether to re-render the editor on each transaction.
* This is legacy behavior that will be removed in future versions.
* @default false
*/
shouldRerenderOnTransaction?: boolean;
};
/**
* This hook allows you to create an editor instance.
* @param options The editor options
* @param deps The dependencies to watch for changes
* @returns The editor instance
* @example const editor = useEditor({ extensions: [...] })
*/
declare function useEditor(options: UseEditorOptions & {
immediatelyRender: false;
}, deps?: DependencyList): Editor | null;
/**
* This hook allows you to create an editor instance.
* @param options The editor options
* @param deps The dependencies to watch for changes
* @returns The editor instance
* @example const editor = useEditor({ extensions: [...] })
*/
declare function useEditor(options: UseEditorOptions, deps?: DependencyList): Editor;
type EditorContextValue = {
editor: Editor | null;
};
declare const EditorContext: React__default.Context<EditorContextValue>;
declare const EditorConsumer: React__default.Consumer<EditorContextValue>;
/**
* A hook to get the current editor instance.
*/
declare const useCurrentEditor: () => EditorContextValue;
type EditorProviderProps = {
children?: ReactNode;
slotBefore?: ReactNode;
slotAfter?: ReactNode;
editorContainerProps?: HTMLAttributes<HTMLDivElement>;
} & UseEditorOptions;
/**
* This is the provider component for the editor.
* It allows the editor to be accessible across the entire component tree
* with `useCurrentEditor`.
*/
declare function EditorProvider({ children, slotAfter, slotBefore, editorContainerProps, ...editorOptions }: EditorProviderProps): react_jsx_runtime.JSX.Element | null;
interface EditorContentProps extends HTMLProps<HTMLDivElement> {
editor: Editor | null;
innerRef?: ForwardedRef<HTMLDivElement | null>;
}
declare class PureEditorContent extends React__default.Component<EditorContentProps, {
hasContentComponentInitialized: boolean;
}> {
editorContentRef: React__default.RefObject<any>;
initialized: boolean;
unsubscribeToContentComponent?: () => void;
constructor(props: EditorContentProps);
componentDidMount(): void;
componentDidUpdate(): void;
init(): void;
componentWillUnmount(): void;
render(): react_jsx_runtime.JSX.Element;
}
declare const EditorContent: React__default.NamedExoticComponent<Omit<EditorContentProps, "ref"> & React__default.RefAttributes<HTMLDivElement>>;
type NodeViewContentProps<T extends keyof React__default.JSX.IntrinsicElements = 'div'> = {
as?: NoInfer<T>;
} & ComponentProps<T>;
declare function NodeViewContent<T extends keyof React__default.JSX.IntrinsicElements = 'div'>({ as: Tag, ...props }: NodeViewContentProps<T>): react_jsx_runtime.JSX.Element;
interface NodeViewWrapperProps {
[key: string]: any;
as?: React__default.ElementType;
}
declare const NodeViewWrapper: React__default.FC<NodeViewWrapperProps>;
interface ReactRendererOptions {
/**
* The editor instance.
* @type {Editor}
*/
editor: Editor;
/**
* The props for the component.
* @type {Record<string, any>}
* @default {}
*/
props?: Record<string, any>;
/**
* The tag name of the element.
* @type {string}
* @default 'div'
*/
as?: string;
/**
* The class name of the element.
* @type {string}
* @default ''
* @example 'foo bar'
*/
className?: string;
}
type ComponentType<R, P> = ComponentClass<P> | FunctionComponent<P> | ForwardRefExoticComponent<PropsWithoutRef<P> & RefAttributes<R>>;
/**
* The ReactRenderer class. It's responsible for rendering React components inside the editor.
* @example
* new ReactRenderer(MyComponent, {
* editor,
* props: {
* foo: 'bar',
* },
* as: 'span',
* })
*/
declare class ReactRenderer<R = unknown, P extends Record<string, any> = object> {
id: string;
editor: Editor;
component: any;
element: HTMLElement;
props: P;
reactElement: ReactNode;
ref: R | null;
/**
* Flag to track if the renderer has been destroyed, preventing queued or asynchronous renders from executing after teardown.
*/
destroyed: boolean;
/**
* 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;
}
interface MarkViewContextProps {
markViewContentRef: (element: HTMLElement | null) => void;
}
declare const ReactMarkViewContext: React__default.Context<MarkViewContextProps>;
type MarkViewContentProps<T extends keyof React__default.JSX.IntrinsicElements = 'span'> = {
as?: T;
} & Omit<React__default.ComponentProps<T>, 'as'>;
declare const MarkViewContent: <T extends keyof React__default.JSX.IntrinsicElements = "span">(props: MarkViewContentProps<T>) => react_jsx_runtime.JSX.Element;
interface ReactMarkViewRendererOptions extends MarkViewRendererOptions {
/**
* The tag name of the element wrapping the React component.
*/
as?: string;
className?: string;
attrs?: {
[key: string]: string;
};
}
declare class ReactMarkView extends MarkView<React__default.ComponentType<MarkViewProps>, ReactMarkViewRendererOptions> {
renderer: ReactRenderer;
contentDOMElement: HTMLElement;
constructor(component: React__default.ComponentType<MarkViewProps>, props: MarkViewProps, options?: Partial<ReactMarkViewRendererOptions>);
get dom(): HTMLElement;
get contentDOM(): HTMLElement;
}
declare function ReactMarkViewRenderer(component: React__default.ComponentType<MarkViewProps>, options?: Partial<ReactMarkViewRendererOptions>): MarkViewRenderer;
type ReactNodeViewProps<T = HTMLElement> = NodeViewProps & {
ref: React__default.RefObject<T | null>;
};
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: Node;
oldDecorations: readonly Decoration[];
oldInnerDecorations: DecorationSource;
newNode: Node;
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;
/**
* 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: Node;
HTMLAttributes: Record<string, any>;
}) => Record<string, string>);
}
declare class ReactNodeView<T = HTMLElement, Component extends ComponentType$1<ReactNodeViewProps<T>> = ComponentType$1<ReactNodeViewProps<T>>, NodeEditor extends Editor = Editor, Options extends ReactNodeViewRendererOptions = ReactNodeViewRendererOptions> extends NodeView<Component, NodeEditor, Options> {
/**
* The renderer instance.
*/
renderer: ReactRenderer<unknown, ReactNodeViewProps<T>>;
/**
* The element that holds the rich-text content of the node.
*/
contentDOMElement: HTMLElement | null;
/**
* The requestAnimationFrame ID used for selection updates.
*/
selectionRafId: number | null;
constructor(component: Component, props: NodeViewRendererProps, options?: Partial<Options>);
private cachedExtensionWithSyncedStorage;
/**
* Returns a proxy of the extension that redirects storage access to the editor's mutable storage.
* This preserves the original prototype chain (instanceof checks, methods like configure/extend work).
* Cached to avoid proxy creation on every update.
*/
get extensionWithSyncedStorage(): NodeViewRendererProps['extension'];
/**
* 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.
*/
declare function ReactNodeViewRenderer<T = HTMLElement>(component: ComponentType$1<ReactNodeViewProps<T>>, options?: Partial<ReactNodeViewRendererOptions>): NodeViewRenderer;
/**
* The shape of the React context used by the `<Tiptap />` components.
*
* The editor instance is always available when using the default `useEditor`
* configuration. For SSR scenarios where `immediatelyRender: false` is used,
* consider using the legacy `EditorProvider` pattern instead.
*/
type TiptapContextType = {
/** The Tiptap editor instance. */
editor: Editor;
};
/**
* React context that stores the current editor instance.
*
* Use `useTiptap()` to read from this context in child components.
*/
declare const TiptapContext: React.Context<TiptapContextType>;
/**
* Hook to read the Tiptap context and access the editor instance.
*
* This is a small convenience wrapper around `useContext(TiptapContext)`.
* The editor is always available when used within a `<Tiptap>` provider.
*
* @returns The current `TiptapContextType` value from the provider.
*
* @example
* ```tsx
* import { useTiptap } from '@tiptap/react'
*
* function Toolbar() {
* const { editor } = useTiptap()
*
* return (
* <button onClick={() => editor.chain().focus().toggleBold().run()}>
* Bold
* </button>
* )
* }
* ```
*/
declare const useTiptap: () => TiptapContextType;
/**
* Select a slice of the editor state using the context-provided editor.
*
* This is a thin wrapper around `useEditorState` that reads the `editor`
* instance from `useTiptap()` so callers don't have to pass it manually.
*
* @typeParam TSelectorResult - The type returned by the selector.
* @param selector - Function that receives the editor state snapshot and
* returns the piece of state you want to subscribe to.
* @param equalityFn - Optional function to compare previous/next selected
* values and avoid unnecessary updates.
* @returns The selected slice of the editor state.
*
* @example
* ```tsx
* function WordCount() {
* const wordCount = useTiptapState(state => {
* const text = state.editor.state.doc.textContent
* return text.split(/\s+/).filter(Boolean).length
* })
*
* return <span>{wordCount} words</span>
* }
* ```
*/
declare function useTiptapState<TSelectorResult>(selector: (context: EditorStateSnapshot<Editor>) => TSelectorResult, equalityFn?: (a: TSelectorResult, b: TSelectorResult | null) => boolean): TSelectorResult;
/**
* Props for the `Tiptap` root/provider component.
*/
type TiptapWrapperProps = {
/**
* The editor instance to provide to child components.
* Use `useEditor()` to create this instance.
*/
editor?: Editor;
/**
* @deprecated Use `editor` instead. Will be removed in the next major version.
*/
instance?: Editor;
children: ReactNode;
};
/**
* Top-level provider component that makes the editor instance available via
* React context to all child components.
*
* This component also provides backwards compatibility with the legacy
* `EditorContext`, so components using `useCurrentEditor()` will work
* inside a `<Tiptap>` provider.
*
* @param props - Component props.
* @returns A context provider element wrapping `children`.
*
* @example
* ```tsx
* import { Tiptap, useEditor } from '@tiptap/react'
*
* function App() {
* const editor = useEditor({ extensions: [...] })
*
* return (
* <Tiptap editor={editor}>
* <Toolbar />
* <Tiptap.Content />
* </Tiptap>
* )
* }
* ```
*/
declare function TiptapWrapper({ editor, instance, children }: TiptapWrapperProps): react_jsx_runtime.JSX.Element;
declare namespace TiptapWrapper {
var displayName: string;
}
/**
* Convenience component that renders `EditorContent` using the context-provided
* editor instance. Use this instead of manually passing the `editor` prop.
*
* @param props - All `EditorContent` props except `editor` and `ref`.
* @returns An `EditorContent` element bound to the context editor.
*
* @example
* ```tsx
* // inside a Tiptap provider
* <Tiptap.Content className="editor" />
* ```
*/
declare function TiptapContent({ ...rest }: Omit<EditorContentProps, 'editor' | 'ref'>): react_jsx_runtime.JSX.Element;
declare namespace TiptapContent {
var displayName: string;
}
/**
* Root `Tiptap` component. Use it as the provider for all child components.
*
* The exported object includes the `Content` subcomponent for rendering the
* editor content area.
*
* This component provides both the new `TiptapContext` (accessed via `useTiptap()`)
* and the legacy `EditorContext` (accessed via `useCurrentEditor()`) for
* backwards compatibility.
*
* For bubble menus and floating menus, import them separately from
* `@tiptap/react/menus` to keep floating-ui as an optional dependency.
*
* @example
* ```tsx
* import { Tiptap, useEditor } from '@tiptap/react'
* import { BubbleMenu } from '@tiptap/react/menus'
*
* function App() {
* const editor = useEditor({ extensions: [...] })
*
* return (
* <Tiptap editor={editor}>
* <Tiptap.Content />
* <BubbleMenu>
* <button onClick={() => editor.chain().focus().toggleBold().run()}>Bold</button>
* </BubbleMenu>
* </Tiptap>
* )
* }
* ```
*/
declare const Tiptap: typeof TiptapWrapper & {
/**
* The Tiptap Content component that renders the EditorContent with the editor instance from the context.
* @see TiptapContent
*/
Content: typeof TiptapContent;
};
type EditorStateSnapshot<TEditor extends Editor | null = Editor | null> = {
editor: TEditor;
transactionNumber: number;
};
type UseEditorStateOptions<TSelectorResult, TEditor extends Editor | null = Editor | null> = {
/**
* The editor instance.
*/
editor: TEditor;
/**
* A selector function to determine the value to compare for re-rendering.
*/
selector: (context: EditorStateSnapshot<TEditor>) => TSelectorResult;
/**
* A custom equality function to determine if the editor should re-render.
* @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 }),
* })
*/
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 }),
* })
*/
declare function useEditorState<TSelectorResult>(options: UseEditorStateOptions<TSelectorResult, Editor | null>): TSelectorResult | null;
interface ReactNodeViewContextProps {
onDragStart?: (event: DragEvent) => void;
nodeViewContentRef?: (element: HTMLElement | null) => void;
/**
* This allows you to add children into the NodeViewContent component.
* This is useful when statically rendering the content of a node view.
*/
nodeViewContentChildren?: ReactNode;
}
declare const ReactNodeViewContext: React.Context<ReactNodeViewContextProps>;
declare const ReactNodeViewContentProvider: ({ children, content }: {
children: ReactNode;
content: ReactNode;
}) => React.FunctionComponentElement<React.ProviderProps<ReactNodeViewContextProps>>;
declare const useReactNodeView: () => ReactNodeViewContextProps;
export { EditorConsumer, EditorContent, type EditorContentProps, EditorContext, type EditorContextValue, EditorProvider, type EditorProviderProps, type EditorStateSnapshot, MarkViewContent, type MarkViewContentProps, type MarkViewContextProps, NodeViewContent, type NodeViewContentProps, NodeViewWrapper, type NodeViewWrapperProps, PureEditorContent, ReactMarkView, ReactMarkViewContext, ReactMarkViewRenderer, type ReactMarkViewRendererOptions, ReactNodeView, ReactNodeViewContentProvider, ReactNodeViewContext, type ReactNodeViewContextProps, type ReactNodeViewProps, ReactNodeViewRenderer, type ReactNodeViewRendererOptions, ReactRenderer, type ReactRendererOptions, Tiptap, TiptapContent, TiptapContext, type TiptapContextType, TiptapWrapper, type TiptapWrapperProps, type UseEditorOptions, type UseEditorStateOptions, useCurrentEditor, useEditor, useEditorState, useReactNodeView, useTiptap, useTiptapState };
+534
View File
@@ -0,0 +1,534 @@
import * as react_jsx_runtime from 'react/jsx-runtime';
import { EditorOptions, Editor, MarkViewRendererOptions, MarkView, MarkViewProps, MarkViewRenderer, NodeViewProps, NodeViewRendererOptions, NodeView, NodeViewRendererProps, NodeViewRenderer } from '@tiptap/core';
export * from '@tiptap/core';
import * as React from 'react';
import React__default, { DependencyList, ReactNode, HTMLAttributes, HTMLProps, ForwardedRef, ComponentProps, ComponentClass, FunctionComponent, ForwardRefExoticComponent, PropsWithoutRef, RefAttributes, ComponentType as ComponentType$1 } from 'react';
import { Node } from '@tiptap/pm/model';
import { Decoration, DecorationSource } from '@tiptap/pm/view';
/**
* The options for the `useEditor` hook.
*/
type UseEditorOptions = Partial<EditorOptions> & {
/**
* Whether to render the editor on the first render.
* If client-side rendering, set this to `true`.
* If server-side rendering, set this to `false`.
* @default true
*/
immediatelyRender?: boolean;
/**
* Whether to re-render the editor on each transaction.
* This is legacy behavior that will be removed in future versions.
* @default false
*/
shouldRerenderOnTransaction?: boolean;
};
/**
* This hook allows you to create an editor instance.
* @param options The editor options
* @param deps The dependencies to watch for changes
* @returns The editor instance
* @example const editor = useEditor({ extensions: [...] })
*/
declare function useEditor(options: UseEditorOptions & {
immediatelyRender: false;
}, deps?: DependencyList): Editor | null;
/**
* This hook allows you to create an editor instance.
* @param options The editor options
* @param deps The dependencies to watch for changes
* @returns The editor instance
* @example const editor = useEditor({ extensions: [...] })
*/
declare function useEditor(options: UseEditorOptions, deps?: DependencyList): Editor;
type EditorContextValue = {
editor: Editor | null;
};
declare const EditorContext: React__default.Context<EditorContextValue>;
declare const EditorConsumer: React__default.Consumer<EditorContextValue>;
/**
* A hook to get the current editor instance.
*/
declare const useCurrentEditor: () => EditorContextValue;
type EditorProviderProps = {
children?: ReactNode;
slotBefore?: ReactNode;
slotAfter?: ReactNode;
editorContainerProps?: HTMLAttributes<HTMLDivElement>;
} & UseEditorOptions;
/**
* This is the provider component for the editor.
* It allows the editor to be accessible across the entire component tree
* with `useCurrentEditor`.
*/
declare function EditorProvider({ children, slotAfter, slotBefore, editorContainerProps, ...editorOptions }: EditorProviderProps): react_jsx_runtime.JSX.Element | null;
interface EditorContentProps extends HTMLProps<HTMLDivElement> {
editor: Editor | null;
innerRef?: ForwardedRef<HTMLDivElement | null>;
}
declare class PureEditorContent extends React__default.Component<EditorContentProps, {
hasContentComponentInitialized: boolean;
}> {
editorContentRef: React__default.RefObject<any>;
initialized: boolean;
unsubscribeToContentComponent?: () => void;
constructor(props: EditorContentProps);
componentDidMount(): void;
componentDidUpdate(): void;
init(): void;
componentWillUnmount(): void;
render(): react_jsx_runtime.JSX.Element;
}
declare const EditorContent: React__default.NamedExoticComponent<Omit<EditorContentProps, "ref"> & React__default.RefAttributes<HTMLDivElement>>;
type NodeViewContentProps<T extends keyof React__default.JSX.IntrinsicElements = 'div'> = {
as?: NoInfer<T>;
} & ComponentProps<T>;
declare function NodeViewContent<T extends keyof React__default.JSX.IntrinsicElements = 'div'>({ as: Tag, ...props }: NodeViewContentProps<T>): react_jsx_runtime.JSX.Element;
interface NodeViewWrapperProps {
[key: string]: any;
as?: React__default.ElementType;
}
declare const NodeViewWrapper: React__default.FC<NodeViewWrapperProps>;
interface ReactRendererOptions {
/**
* The editor instance.
* @type {Editor}
*/
editor: Editor;
/**
* The props for the component.
* @type {Record<string, any>}
* @default {}
*/
props?: Record<string, any>;
/**
* The tag name of the element.
* @type {string}
* @default 'div'
*/
as?: string;
/**
* The class name of the element.
* @type {string}
* @default ''
* @example 'foo bar'
*/
className?: string;
}
type ComponentType<R, P> = ComponentClass<P> | FunctionComponent<P> | ForwardRefExoticComponent<PropsWithoutRef<P> & RefAttributes<R>>;
/**
* The ReactRenderer class. It's responsible for rendering React components inside the editor.
* @example
* new ReactRenderer(MyComponent, {
* editor,
* props: {
* foo: 'bar',
* },
* as: 'span',
* })
*/
declare class ReactRenderer<R = unknown, P extends Record<string, any> = object> {
id: string;
editor: Editor;
component: any;
element: HTMLElement;
props: P;
reactElement: ReactNode;
ref: R | null;
/**
* Flag to track if the renderer has been destroyed, preventing queued or asynchronous renders from executing after teardown.
*/
destroyed: boolean;
/**
* 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;
}
interface MarkViewContextProps {
markViewContentRef: (element: HTMLElement | null) => void;
}
declare const ReactMarkViewContext: React__default.Context<MarkViewContextProps>;
type MarkViewContentProps<T extends keyof React__default.JSX.IntrinsicElements = 'span'> = {
as?: T;
} & Omit<React__default.ComponentProps<T>, 'as'>;
declare const MarkViewContent: <T extends keyof React__default.JSX.IntrinsicElements = "span">(props: MarkViewContentProps<T>) => react_jsx_runtime.JSX.Element;
interface ReactMarkViewRendererOptions extends MarkViewRendererOptions {
/**
* The tag name of the element wrapping the React component.
*/
as?: string;
className?: string;
attrs?: {
[key: string]: string;
};
}
declare class ReactMarkView extends MarkView<React__default.ComponentType<MarkViewProps>, ReactMarkViewRendererOptions> {
renderer: ReactRenderer;
contentDOMElement: HTMLElement;
constructor(component: React__default.ComponentType<MarkViewProps>, props: MarkViewProps, options?: Partial<ReactMarkViewRendererOptions>);
get dom(): HTMLElement;
get contentDOM(): HTMLElement;
}
declare function ReactMarkViewRenderer(component: React__default.ComponentType<MarkViewProps>, options?: Partial<ReactMarkViewRendererOptions>): MarkViewRenderer;
type ReactNodeViewProps<T = HTMLElement> = NodeViewProps & {
ref: React__default.RefObject<T | null>;
};
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: Node;
oldDecorations: readonly Decoration[];
oldInnerDecorations: DecorationSource;
newNode: Node;
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;
/**
* 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: Node;
HTMLAttributes: Record<string, any>;
}) => Record<string, string>);
}
declare class ReactNodeView<T = HTMLElement, Component extends ComponentType$1<ReactNodeViewProps<T>> = ComponentType$1<ReactNodeViewProps<T>>, NodeEditor extends Editor = Editor, Options extends ReactNodeViewRendererOptions = ReactNodeViewRendererOptions> extends NodeView<Component, NodeEditor, Options> {
/**
* The renderer instance.
*/
renderer: ReactRenderer<unknown, ReactNodeViewProps<T>>;
/**
* The element that holds the rich-text content of the node.
*/
contentDOMElement: HTMLElement | null;
/**
* The requestAnimationFrame ID used for selection updates.
*/
selectionRafId: number | null;
constructor(component: Component, props: NodeViewRendererProps, options?: Partial<Options>);
private cachedExtensionWithSyncedStorage;
/**
* Returns a proxy of the extension that redirects storage access to the editor's mutable storage.
* This preserves the original prototype chain (instanceof checks, methods like configure/extend work).
* Cached to avoid proxy creation on every update.
*/
get extensionWithSyncedStorage(): NodeViewRendererProps['extension'];
/**
* 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.
*/
declare function ReactNodeViewRenderer<T = HTMLElement>(component: ComponentType$1<ReactNodeViewProps<T>>, options?: Partial<ReactNodeViewRendererOptions>): NodeViewRenderer;
/**
* The shape of the React context used by the `<Tiptap />` components.
*
* The editor instance is always available when using the default `useEditor`
* configuration. For SSR scenarios where `immediatelyRender: false` is used,
* consider using the legacy `EditorProvider` pattern instead.
*/
type TiptapContextType = {
/** The Tiptap editor instance. */
editor: Editor;
};
/**
* React context that stores the current editor instance.
*
* Use `useTiptap()` to read from this context in child components.
*/
declare const TiptapContext: React.Context<TiptapContextType>;
/**
* Hook to read the Tiptap context and access the editor instance.
*
* This is a small convenience wrapper around `useContext(TiptapContext)`.
* The editor is always available when used within a `<Tiptap>` provider.
*
* @returns The current `TiptapContextType` value from the provider.
*
* @example
* ```tsx
* import { useTiptap } from '@tiptap/react'
*
* function Toolbar() {
* const { editor } = useTiptap()
*
* return (
* <button onClick={() => editor.chain().focus().toggleBold().run()}>
* Bold
* </button>
* )
* }
* ```
*/
declare const useTiptap: () => TiptapContextType;
/**
* Select a slice of the editor state using the context-provided editor.
*
* This is a thin wrapper around `useEditorState` that reads the `editor`
* instance from `useTiptap()` so callers don't have to pass it manually.
*
* @typeParam TSelectorResult - The type returned by the selector.
* @param selector - Function that receives the editor state snapshot and
* returns the piece of state you want to subscribe to.
* @param equalityFn - Optional function to compare previous/next selected
* values and avoid unnecessary updates.
* @returns The selected slice of the editor state.
*
* @example
* ```tsx
* function WordCount() {
* const wordCount = useTiptapState(state => {
* const text = state.editor.state.doc.textContent
* return text.split(/\s+/).filter(Boolean).length
* })
*
* return <span>{wordCount} words</span>
* }
* ```
*/
declare function useTiptapState<TSelectorResult>(selector: (context: EditorStateSnapshot<Editor>) => TSelectorResult, equalityFn?: (a: TSelectorResult, b: TSelectorResult | null) => boolean): TSelectorResult;
/**
* Props for the `Tiptap` root/provider component.
*/
type TiptapWrapperProps = {
/**
* The editor instance to provide to child components.
* Use `useEditor()` to create this instance.
*/
editor?: Editor;
/**
* @deprecated Use `editor` instead. Will be removed in the next major version.
*/
instance?: Editor;
children: ReactNode;
};
/**
* Top-level provider component that makes the editor instance available via
* React context to all child components.
*
* This component also provides backwards compatibility with the legacy
* `EditorContext`, so components using `useCurrentEditor()` will work
* inside a `<Tiptap>` provider.
*
* @param props - Component props.
* @returns A context provider element wrapping `children`.
*
* @example
* ```tsx
* import { Tiptap, useEditor } from '@tiptap/react'
*
* function App() {
* const editor = useEditor({ extensions: [...] })
*
* return (
* <Tiptap editor={editor}>
* <Toolbar />
* <Tiptap.Content />
* </Tiptap>
* )
* }
* ```
*/
declare function TiptapWrapper({ editor, instance, children }: TiptapWrapperProps): react_jsx_runtime.JSX.Element;
declare namespace TiptapWrapper {
var displayName: string;
}
/**
* Convenience component that renders `EditorContent` using the context-provided
* editor instance. Use this instead of manually passing the `editor` prop.
*
* @param props - All `EditorContent` props except `editor` and `ref`.
* @returns An `EditorContent` element bound to the context editor.
*
* @example
* ```tsx
* // inside a Tiptap provider
* <Tiptap.Content className="editor" />
* ```
*/
declare function TiptapContent({ ...rest }: Omit<EditorContentProps, 'editor' | 'ref'>): react_jsx_runtime.JSX.Element;
declare namespace TiptapContent {
var displayName: string;
}
/**
* Root `Tiptap` component. Use it as the provider for all child components.
*
* The exported object includes the `Content` subcomponent for rendering the
* editor content area.
*
* This component provides both the new `TiptapContext` (accessed via `useTiptap()`)
* and the legacy `EditorContext` (accessed via `useCurrentEditor()`) for
* backwards compatibility.
*
* For bubble menus and floating menus, import them separately from
* `@tiptap/react/menus` to keep floating-ui as an optional dependency.
*
* @example
* ```tsx
* import { Tiptap, useEditor } from '@tiptap/react'
* import { BubbleMenu } from '@tiptap/react/menus'
*
* function App() {
* const editor = useEditor({ extensions: [...] })
*
* return (
* <Tiptap editor={editor}>
* <Tiptap.Content />
* <BubbleMenu>
* <button onClick={() => editor.chain().focus().toggleBold().run()}>Bold</button>
* </BubbleMenu>
* </Tiptap>
* )
* }
* ```
*/
declare const Tiptap: typeof TiptapWrapper & {
/**
* The Tiptap Content component that renders the EditorContent with the editor instance from the context.
* @see TiptapContent
*/
Content: typeof TiptapContent;
};
type EditorStateSnapshot<TEditor extends Editor | null = Editor | null> = {
editor: TEditor;
transactionNumber: number;
};
type UseEditorStateOptions<TSelectorResult, TEditor extends Editor | null = Editor | null> = {
/**
* The editor instance.
*/
editor: TEditor;
/**
* A selector function to determine the value to compare for re-rendering.
*/
selector: (context: EditorStateSnapshot<TEditor>) => TSelectorResult;
/**
* A custom equality function to determine if the editor should re-render.
* @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 }),
* })
*/
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 }),
* })
*/
declare function useEditorState<TSelectorResult>(options: UseEditorStateOptions<TSelectorResult, Editor | null>): TSelectorResult | null;
interface ReactNodeViewContextProps {
onDragStart?: (event: DragEvent) => void;
nodeViewContentRef?: (element: HTMLElement | null) => void;
/**
* This allows you to add children into the NodeViewContent component.
* This is useful when statically rendering the content of a node view.
*/
nodeViewContentChildren?: ReactNode;
}
declare const ReactNodeViewContext: React.Context<ReactNodeViewContextProps>;
declare const ReactNodeViewContentProvider: ({ children, content }: {
children: ReactNode;
content: ReactNode;
}) => React.FunctionComponentElement<React.ProviderProps<ReactNodeViewContextProps>>;
declare const useReactNodeView: () => ReactNodeViewContextProps;
export { EditorConsumer, EditorContent, type EditorContentProps, EditorContext, type EditorContextValue, EditorProvider, type EditorProviderProps, type EditorStateSnapshot, MarkViewContent, type MarkViewContentProps, type MarkViewContextProps, NodeViewContent, type NodeViewContentProps, NodeViewWrapper, type NodeViewWrapperProps, PureEditorContent, ReactMarkView, ReactMarkViewContext, ReactMarkViewRenderer, type ReactMarkViewRendererOptions, ReactNodeView, ReactNodeViewContentProvider, ReactNodeViewContext, type ReactNodeViewContextProps, type ReactNodeViewProps, ReactNodeViewRenderer, type ReactNodeViewRendererOptions, ReactRenderer, type ReactRendererOptions, Tiptap, TiptapContent, TiptapContext, type TiptapContextType, TiptapWrapper, type TiptapWrapperProps, type UseEditorOptions, type UseEditorStateOptions, useCurrentEditor, useEditor, useEditorState, useReactNodeView, useTiptap, useTiptapState };
+1131
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+229
View File
@@ -0,0 +1,229 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/menus/index.ts
var index_exports = {};
__export(index_exports, {
BubbleMenu: () => BubbleMenu,
FloatingMenu: () => FloatingMenu
});
module.exports = __toCommonJS(index_exports);
// src/menus/BubbleMenu.tsx
var import_extension_bubble_menu = require("@tiptap/extension-bubble-menu");
var import_react = require("@tiptap/react");
var import_react2 = __toESM(require("react"), 1);
var import_react_dom = require("react-dom");
var import_jsx_runtime = require("react/jsx-runtime");
var BubbleMenu = import_react2.default.forwardRef(
({
pluginKey = "bubbleMenu",
editor,
updateDelay,
resizeDelay,
appendTo,
shouldShow = null,
getReferencedVirtualElement,
options,
children,
...restProps
}, ref) => {
const menuEl = (0, import_react2.useRef)(document.createElement("div"));
if (typeof ref === "function") {
ref(menuEl.current);
} else if (ref) {
ref.current = menuEl.current;
}
const { editor: currentEditor } = (0, import_react.useCurrentEditor)();
const pluginEditor = editor || currentEditor;
const bubbleMenuPluginProps = {
updateDelay,
resizeDelay,
appendTo,
pluginKey,
shouldShow,
getReferencedVirtualElement,
options
};
const bubbleMenuPluginPropsRef = (0, import_react2.useRef)(bubbleMenuPluginProps);
bubbleMenuPluginPropsRef.current = bubbleMenuPluginProps;
const [pluginInitialized, setPluginInitialized] = (0, import_react2.useState)(false);
const skipFirstUpdateRef = (0, import_react2.useRef)(true);
(0, import_react2.useEffect)(() => {
if (pluginEditor == null ? void 0 : pluginEditor.isDestroyed) {
return;
}
if (!pluginEditor) {
console.warn("BubbleMenu component is not rendered inside of an editor component or does not have editor prop.");
return;
}
const bubbleMenuElement = menuEl.current;
bubbleMenuElement.style.visibility = "hidden";
bubbleMenuElement.style.position = "absolute";
const plugin = (0, import_extension_bubble_menu.BubbleMenuPlugin)({
...bubbleMenuPluginPropsRef.current,
editor: pluginEditor,
element: bubbleMenuElement
});
pluginEditor.registerPlugin(plugin);
const createdPluginKey = bubbleMenuPluginPropsRef.current.pluginKey;
skipFirstUpdateRef.current = true;
setPluginInitialized(true);
return () => {
setPluginInitialized(false);
pluginEditor.unregisterPlugin(createdPluginKey);
window.requestAnimationFrame(() => {
if (bubbleMenuElement.parentNode) {
bubbleMenuElement.parentNode.removeChild(bubbleMenuElement);
}
});
};
}, [pluginEditor]);
(0, import_react2.useEffect)(() => {
if (!pluginInitialized || !pluginEditor || pluginEditor.isDestroyed) {
return;
}
if (skipFirstUpdateRef.current) {
skipFirstUpdateRef.current = false;
return;
}
pluginEditor.view.dispatch(
pluginEditor.state.tr.setMeta("bubbleMenu", {
type: "updateOptions",
options: bubbleMenuPluginPropsRef.current
})
);
}, [
pluginInitialized,
pluginEditor,
updateDelay,
resizeDelay,
shouldShow,
options,
appendTo,
getReferencedVirtualElement
]);
return (0, import_react_dom.createPortal)(/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { ...restProps, children }), menuEl.current);
}
);
// src/menus/FloatingMenu.tsx
var import_extension_floating_menu = require("@tiptap/extension-floating-menu");
var import_react3 = require("@tiptap/react");
var import_react4 = __toESM(require("react"), 1);
var import_react_dom2 = require("react-dom");
var import_jsx_runtime2 = require("react/jsx-runtime");
var FloatingMenu = import_react4.default.forwardRef(
({
pluginKey = "floatingMenu",
editor,
updateDelay,
resizeDelay,
appendTo,
shouldShow = null,
options,
children,
...restProps
}, ref) => {
const menuEl = (0, import_react4.useRef)(document.createElement("div"));
if (typeof ref === "function") {
ref(menuEl.current);
} else if (ref) {
ref.current = menuEl.current;
}
const { editor: currentEditor } = (0, import_react3.useCurrentEditor)();
const pluginEditor = editor || currentEditor;
const floatingMenuPluginProps = {
updateDelay,
resizeDelay,
appendTo,
pluginKey,
shouldShow,
options
};
const floatingMenuPluginPropsRef = (0, import_react4.useRef)(floatingMenuPluginProps);
floatingMenuPluginPropsRef.current = floatingMenuPluginProps;
const [pluginInitialized, setPluginInitialized] = (0, import_react4.useState)(false);
const skipFirstUpdateRef = (0, import_react4.useRef)(true);
(0, import_react4.useEffect)(() => {
if (pluginEditor == null ? void 0 : pluginEditor.isDestroyed) {
return;
}
if (!pluginEditor) {
console.warn(
"FloatingMenu component is not rendered inside of an editor component or does not have editor prop."
);
return;
}
const floatingMenuElement = menuEl.current;
floatingMenuElement.style.visibility = "hidden";
floatingMenuElement.style.position = "absolute";
const plugin = (0, import_extension_floating_menu.FloatingMenuPlugin)({
...floatingMenuPluginPropsRef.current,
editor: pluginEditor,
element: floatingMenuElement
});
pluginEditor.registerPlugin(plugin);
const createdPluginKey = floatingMenuPluginPropsRef.current.pluginKey;
skipFirstUpdateRef.current = true;
setPluginInitialized(true);
return () => {
setPluginInitialized(false);
pluginEditor.unregisterPlugin(createdPluginKey);
window.requestAnimationFrame(() => {
if (floatingMenuElement.parentNode) {
floatingMenuElement.parentNode.removeChild(floatingMenuElement);
}
});
};
}, [pluginEditor]);
(0, import_react4.useEffect)(() => {
if (!pluginInitialized || !pluginEditor || pluginEditor.isDestroyed) {
return;
}
if (skipFirstUpdateRef.current) {
skipFirstUpdateRef.current = false;
return;
}
pluginEditor.view.dispatch(
pluginEditor.state.tr.setMeta("floatingMenu", {
type: "updateOptions",
options: floatingMenuPluginPropsRef.current
})
);
}, [pluginInitialized, pluginEditor, updateDelay, resizeDelay, shouldShow, options, appendTo]);
return (0, import_react_dom2.createPortal)(/* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { ...restProps, children }), menuEl.current);
}
);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
BubbleMenu,
FloatingMenu
});
//# sourceMappingURL=index.cjs.map
File diff suppressed because one or more lines are too long
+19
View File
@@ -0,0 +1,19 @@
import { BubbleMenuPluginProps } from '@tiptap/extension-bubble-menu';
import React from 'react';
import { FloatingMenuPluginProps } from '@tiptap/extension-floating-menu';
type Optional$1<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;
type BubbleMenuProps = Optional$1<Omit<Optional$1<BubbleMenuPluginProps, 'pluginKey'>, 'element'>, 'editor'> & React.HTMLAttributes<HTMLDivElement>;
declare const BubbleMenu: React.ForwardRefExoticComponent<Pick<Partial<Omit<Optional$1<BubbleMenuPluginProps, "pluginKey">, "element">>, "editor"> & Omit<Omit<Optional$1<BubbleMenuPluginProps, "pluginKey">, "element">, "editor"> & React.HTMLAttributes<HTMLDivElement> & React.RefAttributes<HTMLDivElement>>;
type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;
type FloatingMenuProps = Omit<Optional<FloatingMenuPluginProps, 'pluginKey'>, 'element' | 'editor'> & {
editor: FloatingMenuPluginProps['editor'] | null;
options?: FloatingMenuPluginProps['options'];
} & React.HTMLAttributes<HTMLDivElement>;
declare const FloatingMenu: React.ForwardRefExoticComponent<Omit<Optional<FloatingMenuPluginProps, "pluginKey">, "editor" | "element"> & {
editor: FloatingMenuPluginProps["editor"] | null;
options?: FloatingMenuPluginProps["options"];
} & React.HTMLAttributes<HTMLDivElement> & React.RefAttributes<HTMLDivElement>>;
export { BubbleMenu, type BubbleMenuProps, FloatingMenu, type FloatingMenuProps };
+19
View File
@@ -0,0 +1,19 @@
import { BubbleMenuPluginProps } from '@tiptap/extension-bubble-menu';
import React from 'react';
import { FloatingMenuPluginProps } from '@tiptap/extension-floating-menu';
type Optional$1<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;
type BubbleMenuProps = Optional$1<Omit<Optional$1<BubbleMenuPluginProps, 'pluginKey'>, 'element'>, 'editor'> & React.HTMLAttributes<HTMLDivElement>;
declare const BubbleMenu: React.ForwardRefExoticComponent<Pick<Partial<Omit<Optional$1<BubbleMenuPluginProps, "pluginKey">, "element">>, "editor"> & Omit<Omit<Optional$1<BubbleMenuPluginProps, "pluginKey">, "element">, "editor"> & React.HTMLAttributes<HTMLDivElement> & React.RefAttributes<HTMLDivElement>>;
type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;
type FloatingMenuProps = Omit<Optional<FloatingMenuPluginProps, 'pluginKey'>, 'element' | 'editor'> & {
editor: FloatingMenuPluginProps['editor'] | null;
options?: FloatingMenuPluginProps['options'];
} & React.HTMLAttributes<HTMLDivElement>;
declare const FloatingMenu: React.ForwardRefExoticComponent<Omit<Optional<FloatingMenuPluginProps, "pluginKey">, "editor" | "element"> & {
editor: FloatingMenuPluginProps["editor"] | null;
options?: FloatingMenuPluginProps["options"];
} & React.HTMLAttributes<HTMLDivElement> & React.RefAttributes<HTMLDivElement>>;
export { BubbleMenu, type BubbleMenuProps, FloatingMenu, type FloatingMenuProps };
+191
View File
@@ -0,0 +1,191 @@
// src/menus/BubbleMenu.tsx
import { BubbleMenuPlugin } from "@tiptap/extension-bubble-menu";
import { useCurrentEditor } from "@tiptap/react";
import React, { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { jsx } from "react/jsx-runtime";
var BubbleMenu = React.forwardRef(
({
pluginKey = "bubbleMenu",
editor,
updateDelay,
resizeDelay,
appendTo,
shouldShow = null,
getReferencedVirtualElement,
options,
children,
...restProps
}, ref) => {
const menuEl = useRef(document.createElement("div"));
if (typeof ref === "function") {
ref(menuEl.current);
} else if (ref) {
ref.current = menuEl.current;
}
const { editor: currentEditor } = useCurrentEditor();
const pluginEditor = editor || currentEditor;
const bubbleMenuPluginProps = {
updateDelay,
resizeDelay,
appendTo,
pluginKey,
shouldShow,
getReferencedVirtualElement,
options
};
const bubbleMenuPluginPropsRef = useRef(bubbleMenuPluginProps);
bubbleMenuPluginPropsRef.current = bubbleMenuPluginProps;
const [pluginInitialized, setPluginInitialized] = useState(false);
const skipFirstUpdateRef = useRef(true);
useEffect(() => {
if (pluginEditor == null ? void 0 : pluginEditor.isDestroyed) {
return;
}
if (!pluginEditor) {
console.warn("BubbleMenu component is not rendered inside of an editor component or does not have editor prop.");
return;
}
const bubbleMenuElement = menuEl.current;
bubbleMenuElement.style.visibility = "hidden";
bubbleMenuElement.style.position = "absolute";
const plugin = BubbleMenuPlugin({
...bubbleMenuPluginPropsRef.current,
editor: pluginEditor,
element: bubbleMenuElement
});
pluginEditor.registerPlugin(plugin);
const createdPluginKey = bubbleMenuPluginPropsRef.current.pluginKey;
skipFirstUpdateRef.current = true;
setPluginInitialized(true);
return () => {
setPluginInitialized(false);
pluginEditor.unregisterPlugin(createdPluginKey);
window.requestAnimationFrame(() => {
if (bubbleMenuElement.parentNode) {
bubbleMenuElement.parentNode.removeChild(bubbleMenuElement);
}
});
};
}, [pluginEditor]);
useEffect(() => {
if (!pluginInitialized || !pluginEditor || pluginEditor.isDestroyed) {
return;
}
if (skipFirstUpdateRef.current) {
skipFirstUpdateRef.current = false;
return;
}
pluginEditor.view.dispatch(
pluginEditor.state.tr.setMeta("bubbleMenu", {
type: "updateOptions",
options: bubbleMenuPluginPropsRef.current
})
);
}, [
pluginInitialized,
pluginEditor,
updateDelay,
resizeDelay,
shouldShow,
options,
appendTo,
getReferencedVirtualElement
]);
return createPortal(/* @__PURE__ */ jsx("div", { ...restProps, children }), menuEl.current);
}
);
// src/menus/FloatingMenu.tsx
import { FloatingMenuPlugin } from "@tiptap/extension-floating-menu";
import { useCurrentEditor as useCurrentEditor2 } from "@tiptap/react";
import React2, { useEffect as useEffect2, useRef as useRef2, useState as useState2 } from "react";
import { createPortal as createPortal2 } from "react-dom";
import { jsx as jsx2 } from "react/jsx-runtime";
var FloatingMenu = React2.forwardRef(
({
pluginKey = "floatingMenu",
editor,
updateDelay,
resizeDelay,
appendTo,
shouldShow = null,
options,
children,
...restProps
}, ref) => {
const menuEl = useRef2(document.createElement("div"));
if (typeof ref === "function") {
ref(menuEl.current);
} else if (ref) {
ref.current = menuEl.current;
}
const { editor: currentEditor } = useCurrentEditor2();
const pluginEditor = editor || currentEditor;
const floatingMenuPluginProps = {
updateDelay,
resizeDelay,
appendTo,
pluginKey,
shouldShow,
options
};
const floatingMenuPluginPropsRef = useRef2(floatingMenuPluginProps);
floatingMenuPluginPropsRef.current = floatingMenuPluginProps;
const [pluginInitialized, setPluginInitialized] = useState2(false);
const skipFirstUpdateRef = useRef2(true);
useEffect2(() => {
if (pluginEditor == null ? void 0 : pluginEditor.isDestroyed) {
return;
}
if (!pluginEditor) {
console.warn(
"FloatingMenu component is not rendered inside of an editor component or does not have editor prop."
);
return;
}
const floatingMenuElement = menuEl.current;
floatingMenuElement.style.visibility = "hidden";
floatingMenuElement.style.position = "absolute";
const plugin = FloatingMenuPlugin({
...floatingMenuPluginPropsRef.current,
editor: pluginEditor,
element: floatingMenuElement
});
pluginEditor.registerPlugin(plugin);
const createdPluginKey = floatingMenuPluginPropsRef.current.pluginKey;
skipFirstUpdateRef.current = true;
setPluginInitialized(true);
return () => {
setPluginInitialized(false);
pluginEditor.unregisterPlugin(createdPluginKey);
window.requestAnimationFrame(() => {
if (floatingMenuElement.parentNode) {
floatingMenuElement.parentNode.removeChild(floatingMenuElement);
}
});
};
}, [pluginEditor]);
useEffect2(() => {
if (!pluginInitialized || !pluginEditor || pluginEditor.isDestroyed) {
return;
}
if (skipFirstUpdateRef.current) {
skipFirstUpdateRef.current = false;
return;
}
pluginEditor.view.dispatch(
pluginEditor.state.tr.setMeta("floatingMenu", {
type: "updateOptions",
options: floatingMenuPluginPropsRef.current
})
);
}, [pluginInitialized, pluginEditor, updateDelay, resizeDelay, shouldShow, options, appendTo]);
return createPortal2(/* @__PURE__ */ jsx2("div", { ...restProps, children }), menuEl.current);
}
);
export {
BubbleMenu,
FloatingMenu
};
//# sourceMappingURL=index.js.map
File diff suppressed because one or more lines are too long
+76
View File
@@ -0,0 +1,76 @@
{
"name": "@tiptap/react",
"description": "React components for tiptap",
"version": "3.19.0",
"homepage": "https://tiptap.dev",
"keywords": [
"tiptap",
"tiptap react components"
],
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"exports": {
".": {
"types": {
"import": "./dist/index.d.ts",
"require": "./dist/index.d.cts"
},
"import": "./dist/index.js",
"require": "./dist/index.cjs"
},
"./menus": {
"types": {
"import": "./dist/menus/index.d.ts",
"require": "./dist/menus/index.d.cts"
},
"import": "./dist/menus/index.js",
"require": "./dist/menus/index.cjs"
}
},
"main": "dist/index.cjs",
"module": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"files": [
"src",
"dist"
],
"dependencies": {
"@types/use-sync-external-store": "^0.0.6",
"fast-equals": "^5.3.3",
"use-sync-external-store": "^1.4.0"
},
"devDependencies": {
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"@tiptap/core": "^3.19.0",
"@tiptap/pm": "^3.19.0"
},
"optionalDependencies": {
"@tiptap/extension-bubble-menu": "^3.19.0",
"@tiptap/extension-floating-menu": "^3.19.0"
},
"peerDependencies": {
"react": "^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0",
"@types/react": "^17.0.0 || ^18.0.0 || ^19.0.0",
"@types/react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0",
"@tiptap/core": "^3.19.0",
"@tiptap/pm": "^3.19.0"
},
"repository": {
"type": "git",
"url": "https://github.com/ueberdosis/tiptap",
"directory": "packages/react"
},
"sideEffects": false,
"scripts": {
"build": "tsup",
"lint": "prettier ./src/ --check && eslint --cache --quiet --no-error-on-unmatched-pattern ./src/"
}
}
+60
View File
@@ -0,0 +1,60 @@
import type { Editor } from '@tiptap/core'
import type { HTMLAttributes, ReactNode } from 'react'
import React, { createContext, useContext, useMemo } from 'react'
import { EditorContent } from './EditorContent.js'
import type { UseEditorOptions } from './useEditor.js'
import { useEditor } from './useEditor.js'
export type EditorContextValue = {
editor: Editor | null
}
export const EditorContext = createContext<EditorContextValue>({
editor: null,
})
export const EditorConsumer = EditorContext.Consumer
/**
* A hook to get the current editor instance.
*/
export const useCurrentEditor = () => useContext(EditorContext)
export type EditorProviderProps = {
children?: ReactNode
slotBefore?: ReactNode
slotAfter?: ReactNode
editorContainerProps?: HTMLAttributes<HTMLDivElement>
} & UseEditorOptions
/**
* This is the provider component for the editor.
* It allows the editor to be accessible across the entire component tree
* with `useCurrentEditor`.
*/
export function EditorProvider({
children,
slotAfter,
slotBefore,
editorContainerProps = {},
...editorOptions
}: EditorProviderProps) {
const editor = useEditor(editorOptions)
const contextValue = useMemo(() => ({ editor }), [editor])
if (!editor) {
return null
}
return (
<EditorContext.Provider value={contextValue}>
{slotBefore}
<EditorConsumer>
{({ editor: currentEditor }) => <EditorContent editor={currentEditor} {...editorContainerProps} />}
</EditorConsumer>
{children}
{slotAfter}
</EditorContext.Provider>
)
}
+13
View File
@@ -0,0 +1,13 @@
import type { Editor } from '@tiptap/core'
import type { ReactPortal } from 'react'
import type { ReactRenderer } from './ReactRenderer.js'
export type EditorWithContentComponent = Editor & { contentComponent?: ContentComponent | null }
export type ContentComponent = {
setRenderer(id: string, renderer: ReactRenderer): void
removeRenderer(id: string): void
subscribe: (callback: () => void) => () => void
getSnapshot: () => Record<string, ReactPortal>
getServerSnapshot: () => Record<string, ReactPortal>
}
+229
View File
@@ -0,0 +1,229 @@
import type { Editor } from '@tiptap/core'
import type { ForwardedRef, HTMLProps, LegacyRef, MutableRefObject } from 'react'
import React, { forwardRef } from 'react'
import ReactDOM from 'react-dom'
import { useSyncExternalStore } from 'use-sync-external-store/shim/index.js'
import type { ContentComponent, EditorWithContentComponent } from './Editor.js'
import type { ReactRenderer } from './ReactRenderer.js'
const mergeRefs = <T extends HTMLDivElement>(...refs: Array<MutableRefObject<T> | LegacyRef<T> | undefined>) => {
return (node: T) => {
refs.forEach(ref => {
if (typeof ref === 'function') {
ref(node)
} else if (ref) {
;(ref as MutableRefObject<T | null>).current = node
}
})
}
}
/**
* This component renders all of the editor's node views.
*/
const Portals: React.FC<{ contentComponent: ContentComponent }> = ({ contentComponent }) => {
// For performance reasons, we render the node view portals on state changes only
const renderers = useSyncExternalStore(
contentComponent.subscribe,
contentComponent.getSnapshot,
contentComponent.getServerSnapshot,
)
// This allows us to directly render the portals without any additional wrapper
return <>{Object.values(renderers)}</>
}
export interface EditorContentProps extends HTMLProps<HTMLDivElement> {
editor: Editor | null
innerRef?: ForwardedRef<HTMLDivElement | null>
}
function getInstance(): ContentComponent {
const subscribers = new Set<() => void>()
let renderers: Record<string, React.ReactPortal> = {}
return {
/**
* Subscribe to the editor instance's changes.
*/
subscribe(callback: () => void) {
subscribers.add(callback)
return () => {
subscribers.delete(callback)
}
},
getSnapshot() {
return renderers
},
getServerSnapshot() {
return renderers
},
/**
* Adds a new NodeView Renderer to the editor.
*/
setRenderer(id: string, renderer: ReactRenderer) {
renderers = {
...renderers,
[id]: ReactDOM.createPortal(renderer.reactElement, renderer.element, id),
}
subscribers.forEach(subscriber => subscriber())
},
/**
* Removes a NodeView Renderer from the editor.
*/
removeRenderer(id: string) {
const nextRenderers = { ...renderers }
delete nextRenderers[id]
renderers = nextRenderers
subscribers.forEach(subscriber => subscriber())
},
}
}
export class PureEditorContent extends React.Component<
EditorContentProps,
{ hasContentComponentInitialized: boolean }
> {
editorContentRef: React.RefObject<any>
initialized: boolean
unsubscribeToContentComponent?: () => void
constructor(props: EditorContentProps) {
super(props)
this.editorContentRef = React.createRef()
this.initialized = false
this.state = {
hasContentComponentInitialized: Boolean((props.editor as EditorWithContentComponent | null)?.contentComponent),
}
}
componentDidMount() {
this.init()
}
componentDidUpdate() {
this.init()
}
init() {
const editor = this.props.editor as EditorWithContentComponent | null
if (editor && !editor.isDestroyed && editor.view.dom?.parentNode) {
if (editor.contentComponent) {
return
}
const element = this.editorContentRef.current
element.append(...editor.view.dom.parentNode.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 as EditorWithContentComponent | null
if (!editor) {
return
}
this.initialized = false
if (!editor.isDestroyed) {
editor.view.setProps({
nodeViews: {},
})
}
if (this.unsubscribeToContentComponent) {
this.unsubscribeToContentComponent()
}
editor.contentComponent = null
// try to reset the editor element
// may fail if this editor's view.dom was never initialized/mounted yet
try {
if (!editor.view.dom?.parentNode) {
return
}
// TODO using the new editor.mount method might allow us to remove this
const newElement = document.createElement('div')
newElement.append(...editor.view.dom.parentNode.childNodes)
editor.setOptions({
element: newElement,
})
} catch {
// do nothing, nothing to reset
}
}
render() {
const { editor, innerRef, ...rest } = this.props
return (
<>
<div ref={mergeRefs(innerRef, this.editorContentRef)} {...rest} />
{/* @ts-ignore */}
{editor?.contentComponent && <Portals contentComponent={editor.contentComponent} />}
</>
)
}
}
// EditorContent should be re-created whenever the Editor instance changes
const EditorContentWithKey = forwardRef<HTMLDivElement, EditorContentProps>(
(props: Omit<EditorContentProps, 'innerRef'>, 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,
})
},
)
export const EditorContent = React.memo(EditorContentWithKey)
+30
View File
@@ -0,0 +1,30 @@
import type { ComponentProps } from 'react'
import React from 'react'
import { useReactNodeView } from './useReactNodeView.js'
export type NodeViewContentProps<T extends keyof React.JSX.IntrinsicElements = 'div'> = {
as?: NoInfer<T>
} & ComponentProps<T>
export function NodeViewContent<T extends keyof React.JSX.IntrinsicElements = 'div'>({
as: Tag = 'div' as T,
...props
}: NodeViewContentProps<T>) {
const { nodeViewContentRef, nodeViewContentChildren } = useReactNodeView()
return (
// @ts-ignore
<Tag
{...props}
ref={nodeViewContentRef}
data-node-view-content=""
style={{
whiteSpace: 'pre-wrap',
...props.style,
}}
>
{nodeViewContentChildren}
</Tag>
)
}
+27
View File
@@ -0,0 +1,27 @@
import React from 'react'
import { useReactNodeView } from './useReactNodeView.js'
export interface NodeViewWrapperProps {
[key: string]: any
as?: React.ElementType
}
export const NodeViewWrapper: React.FC<NodeViewWrapperProps> = React.forwardRef((props, ref) => {
const { onDragStart } = useReactNodeView()
const Tag = props.as || 'div'
return (
// @ts-ignore
<Tag
{...props}
ref={ref}
data-node-view-wrapper=""
onDragStart={onDragStart}
style={{
whiteSpace: 'normal',
...props.style,
}}
/>
)
})
+106
View File
@@ -0,0 +1,106 @@
/* eslint-disable @typescript-eslint/no-shadow */
import type { MarkViewProps, MarkViewRenderer, MarkViewRendererOptions } from '@tiptap/core'
import { MarkView } from '@tiptap/core'
import React from 'react'
// import { flushSync } from 'react-dom'
import { ReactRenderer } from './ReactRenderer.js'
export interface MarkViewContextProps {
markViewContentRef: (element: HTMLElement | null) => void
}
export const ReactMarkViewContext = React.createContext<MarkViewContextProps>({
markViewContentRef: () => {
// do nothing
},
})
export type MarkViewContentProps<T extends keyof React.JSX.IntrinsicElements = 'span'> = {
as?: T
} & Omit<React.ComponentProps<T>, 'as'>
export const MarkViewContent = <T extends keyof React.JSX.IntrinsicElements = 'span'>(
props: MarkViewContentProps<T>,
) => {
const { as: Tag = 'span', ...rest } = props
const { markViewContentRef } = React.useContext(ReactMarkViewContext)
return (
// @ts-ignore
<Tag {...rest} ref={markViewContentRef} data-mark-view-content="" />
)
}
export interface ReactMarkViewRendererOptions extends MarkViewRendererOptions {
/**
* The tag name of the element wrapping the React component.
*/
as?: string
className?: string
attrs?: { [key: string]: string }
}
export class ReactMarkView extends MarkView<React.ComponentType<MarkViewProps>, ReactMarkViewRendererOptions> {
renderer: ReactRenderer
contentDOMElement: HTMLElement
constructor(
component: React.ComponentType<MarkViewProps>,
props: MarkViewProps,
options?: Partial<ReactMarkViewRendererOptions>,
) {
super(component, props, options)
const { as = 'span', attrs, className = '' } = options || {}
const componentProps = { ...props, updateAttributes: this.updateAttributes.bind(this) } satisfies MarkViewProps
this.contentDOMElement = document.createElement('span')
const markViewContentRef: MarkViewContextProps['markViewContentRef'] = el => {
if (el && !el.contains(this.contentDOMElement)) {
el.appendChild(this.contentDOMElement)
}
}
const context: MarkViewContextProps = {
markViewContentRef,
}
// 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 ReactMarkViewProvider: React.FunctionComponent<MarkViewProps> = React.memo(componentProps => {
return (
<ReactMarkViewContext.Provider value={context}>
{React.createElement(component, componentProps)}
</ReactMarkViewContext.Provider>
)
})
ReactMarkViewProvider.displayName = 'ReactMarkView'
this.renderer = new ReactRenderer(ReactMarkViewProvider, {
editor: props.editor,
props: componentProps,
as,
className: `mark-${props.mark.type.name} ${className}`.trim(),
})
if (attrs) {
this.renderer.updateAttributes(attrs)
}
}
get dom() {
return this.renderer.element
}
get contentDOM() {
return this.contentDOMElement
}
}
export function ReactMarkViewRenderer(
component: React.ComponentType<MarkViewProps>,
options: Partial<ReactMarkViewRendererOptions> = {},
): MarkViewRenderer {
return props => new ReactMarkView(component, props, options)
}
+387
View File
@@ -0,0 +1,387 @@
import type {
DecorationWithType,
Editor,
NodeViewRenderer,
NodeViewRendererOptions,
NodeViewRendererProps,
} from '@tiptap/core'
import { getRenderedAttributes, NodeView } from '@tiptap/core'
import type { Node, Node as ProseMirrorNode } from '@tiptap/pm/model'
import type { Decoration, DecorationSource, NodeView as ProseMirrorNodeView } from '@tiptap/pm/view'
import type { ComponentType, NamedExoticComponent } from 'react'
import { createElement, createRef, memo } from 'react'
import type { EditorWithContentComponent } from './Editor.js'
import { ReactRenderer } from './ReactRenderer.js'
import type { ReactNodeViewProps } from './types.js'
import type { ReactNodeViewContextProps } from './useReactNodeView.js'
import { ReactNodeViewContext } from './useReactNodeView.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: readonly Decoration[]
oldInnerDecorations: DecorationSource
newNode: ProseMirrorNode
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
/**
* 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 class ReactNodeView<
T = HTMLElement,
Component extends ComponentType<ReactNodeViewProps<T>> = ComponentType<ReactNodeViewProps<T>>,
NodeEditor extends Editor = Editor,
Options extends ReactNodeViewRendererOptions = ReactNodeViewRendererOptions,
> extends NodeView<Component, NodeEditor, Options> {
/**
* The renderer instance.
*/
renderer!: ReactRenderer<unknown, ReactNodeViewProps<T>>
/**
* The element that holds the rich-text content of the node.
*/
contentDOMElement!: HTMLElement | null
/**
* The requestAnimationFrame ID used for selection updates.
*/
selectionRafId: number | null = null
constructor(component: Component, props: NodeViewRendererProps, options?: Partial<Options>) {
super(component, props, options)
if (!this.node.isLeaf) {
if (this.options.contentDOMElementTag) {
this.contentDOMElement = document.createElement(this.options.contentDOMElementTag)
} else {
this.contentDOMElement = document.createElement(this.node.isInline ? 'span' : 'div')
}
this.contentDOMElement.dataset.nodeViewContentReact = ''
this.contentDOMElement.dataset.nodeViewWrapper = ''
// 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'
const contentTarget = this.dom.querySelector('[data-node-view-content]')
if (!contentTarget) {
return
}
contentTarget.appendChild(this.contentDOMElement)
}
}
private cachedExtensionWithSyncedStorage: NodeViewRendererProps['extension'] | null = null
/**
* Returns a proxy of the extension that redirects storage access to the editor's mutable storage.
* This preserves the original prototype chain (instanceof checks, methods like configure/extend work).
* Cached to avoid proxy creation on every update.
*/
get extensionWithSyncedStorage(): NodeViewRendererProps['extension'] {
if (!this.cachedExtensionWithSyncedStorage) {
const editor = this.editor
const extension = this.extension
this.cachedExtensionWithSyncedStorage = new Proxy(extension, {
get(target, prop, receiver) {
if (prop === 'storage') {
return editor.storage[extension.name as keyof typeof editor.storage] ?? {}
}
return Reflect.get(target, prop, receiver)
},
})
}
return this.cachedExtensionWithSyncedStorage
}
/**
* Setup the React component.
* Called on initialization.
*/
mount() {
const props = {
editor: this.editor,
node: this.node,
decorations: this.decorations as DecorationWithType[],
innerDecorations: this.innerDecorations,
view: this.view,
selected: false,
extension: this.extensionWithSyncedStorage,
HTMLAttributes: this.HTMLAttributes,
getPos: () => this.getPos(),
updateAttributes: (attributes = {}) => this.updateAttributes(attributes),
deleteNode: () => this.deleteNode(),
ref: createRef<T>(),
} satisfies ReactNodeViewProps<T>
if (!(this.component as any).displayName) {
const capitalizeFirstChar = (string: string): string => {
return string.charAt(0).toUpperCase() + string.substring(1)
}
this.component.displayName = capitalizeFirstChar(this.extension.name)
}
const onDragStart = this.onDragStart.bind(this)
const nodeViewContentRef: ReactNodeViewContextProps['nodeViewContentRef'] = element => {
if (element && this.contentDOMElement && element.firstChild !== this.contentDOMElement) {
// remove the nodeViewWrapper attribute from the element
if (element.hasAttribute('data-node-view-wrapper')) {
element.removeAttribute('data-node-view-wrapper')
}
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: NamedExoticComponent<ReactNodeViewProps<T>> = memo(componentProps => {
return (
<ReactNodeViewContext.Provider value={context}>
{createElement(Component, componentProps)}
</ReactNodeViewContext.Provider>
)
})
ReactNodeViewProvider.displayName = 'ReactNodeView'
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.renderer = new ReactRenderer(ReactNodeViewProvider, {
editor: this.editor,
props,
as,
className: `node-${this.node.type.name} ${className}`.trim(),
})
this.editor.on('selectionUpdate', this.handleSelectionUpdate)
this.updateElementAttributes()
}
/**
* Return the DOM element.
* This is the element that will be used to display the node view.
*/
get dom() {
if (
this.renderer.element.firstElementChild &&
!this.renderer.element.firstElementChild?.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() {
if (this.selectionRafId) {
cancelAnimationFrame(this.selectionRafId)
this.selectionRafId = null
}
this.selectionRafId = requestAnimationFrame(() => {
this.selectionRafId = null
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: Node, decorations: readonly Decoration[], innerDecorations: DecorationSource): boolean {
const rerenderComponent = (props?: Record<string, any>) => {
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, extension: this.extensionWithSyncedStorage }),
})
}
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, extension: this.extensionWithSyncedStorage })
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
if (this.selectionRafId) {
cancelAnimationFrame(this.selectionRafId)
this.selectionRafId = 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: Record<string, string> = {}
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.
*/
export function ReactNodeViewRenderer<T = HTMLElement>(
component: ComponentType<ReactNodeViewProps<T>>,
options?: Partial<ReactNodeViewRendererOptions>,
): NodeViewRenderer {
return props => {
// try to get the parent component
// this is important for vue devtools to show the component hierarchy correctly
// maybe its `undefined` because <editor-content> isnt rendered yet
if (!(props.editor as EditorWithContentComponent).contentComponent) {
return {} as unknown as ProseMirrorNodeView
}
return new ReactNodeView<T>(component, props, options)
}
}
+282
View File
@@ -0,0 +1,282 @@
import type { Editor } from '@tiptap/core'
import type {
ComponentClass,
ForwardRefExoticComponent,
FunctionComponent,
PropsWithoutRef,
ReactNode,
RefAttributes,
} from 'react'
import { version as reactVersion } from 'react'
import { flushSync } from 'react-dom'
import type { EditorWithContentComponent } from './Editor.js'
/**
* Check if a component is a class component.
* @param Component
* @returns {boolean}
*/
function isClassComponent(Component: any) {
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: any) {
return !!(
typeof Component === 'object' &&
Component.$$typeof &&
(Component.$$typeof.toString() === 'Symbol(react.forward_ref)' ||
Component.$$typeof.description === 'react.forward_ref')
)
}
/**
* Check if a component is a memoized component.
* @param Component
* @returns {boolean}
*/
function isMemoComponent(Component: any) {
return !!(
typeof Component === 'object' &&
Component.$$typeof &&
(Component.$$typeof.toString() === 'Symbol(react.memo)' || Component.$$typeof.description === 'react.memo')
)
}
/**
* Check if a component can safely receive a ref prop.
* This includes class components, forwardRef components, and memoized components
* that wrap forwardRef or class components.
* @param Component
* @returns {boolean}
*/
function canReceiveRef(Component: any) {
// Check if it's a class component
if (isClassComponent(Component)) {
return true
}
// Check if it's a forwardRef component
if (isForwardRefComponent(Component)) {
return true
}
// Check if it's a memoized component
if (isMemoComponent(Component)) {
// For memoized components, check the wrapped component
const wrappedComponent = Component.type
if (wrappedComponent) {
return isClassComponent(wrappedComponent) || isForwardRefComponent(wrappedComponent)
}
}
return false
}
/**
* Check if we're running React 19+ by detecting if function components support ref props
* @returns {boolean}
*/
function isReact19Plus(): boolean {
// React 19 is detected by checking React version if available
// In practice, we'll use a more conservative approach and assume React 18 behavior
// unless we can definitively detect React 19
try {
// @ts-ignore
if (reactVersion) {
const majorVersion = parseInt(reactVersion.split('.')[0], 10)
return majorVersion >= 19
}
} catch {
// Fallback to React 18 behavior if we can't determine version
}
return false
}
export interface ReactRendererOptions {
/**
* The editor instance.
* @type {Editor}
*/
editor: Editor
/**
* The props for the component.
* @type {Record<string, any>}
* @default {}
*/
props?: Record<string, any>
/**
* The tag name of the element.
* @type {string}
* @default 'div'
*/
as?: string
/**
* The class name of the element.
* @type {string}
* @default ''
* @example 'foo bar'
*/
className?: string
}
type ComponentType<R, P> =
| ComponentClass<P>
| FunctionComponent<P>
| ForwardRefExoticComponent<PropsWithoutRef<P> & RefAttributes<R>>
/**
* The ReactRenderer class. It's responsible for rendering React components inside the editor.
* @example
* new ReactRenderer(MyComponent, {
* editor,
* props: {
* foo: 'bar',
* },
* as: 'span',
* })
*/
export class ReactRenderer<R = unknown, P extends Record<string, any> = object> {
id: string
editor: Editor
component: any
element: HTMLElement
props: P
reactElement: ReactNode
ref: R | null = null
/**
* Flag to track if the renderer has been destroyed, preventing queued or asynchronous renders from executing after teardown.
*/
destroyed = false
/**
* Immediately creates element and renders the provided React component.
*/
constructor(
component: ComponentType<R, P>,
{ editor, props = {}, as = 'div', className = '' }: ReactRendererOptions,
) {
this.id = Math.floor(Math.random() * 0xffffffff).toString()
this.component = component
this.editor = editor as EditorWithContentComponent
this.props = props as P
this.element = document.createElement(as)
this.element.classList.add('react-renderer')
if (className) {
this.element.classList.add(...className.split(' '))
}
// If the editor is already initialized, we will need to
// synchronously render the component to ensure it renders
// together with Prosemirror's rendering.
if (this.editor.isInitialized) {
flushSync(() => {
this.render()
})
} else {
queueMicrotask(() => {
if (this.destroyed) {
return
}
this.render()
})
}
}
/**
* Render the React component.
*/
render(): void {
if (this.destroyed) {
return
}
const Component = this.component
const props = this.props
const editor = this.editor as EditorWithContentComponent
// Handle ref forwarding with React 18/19 compatibility
const isReact19 = isReact19Plus()
const componentCanReceiveRef = canReceiveRef(Component)
const elementProps = { ...props }
// Always remove ref if the component cannot receive it (unless React 19+)
if (elementProps.ref && !(isReact19 || componentCanReceiveRef)) {
delete elementProps.ref
}
// Only assign our own ref if allowed
if (!elementProps.ref && (isReact19 || componentCanReceiveRef)) {
// @ts-ignore - Setting ref prop for compatible components
elementProps.ref = (ref: R) => {
this.ref = ref
}
}
this.reactElement = <Component {...elementProps} />
editor?.contentComponent?.setRenderer(this.id, this)
}
/**
* Re-renders the React component with new props.
*/
updateProps(props: Record<string, any> = {}): void {
if (this.destroyed) {
return
}
this.props = {
...this.props,
...props,
}
this.render()
}
/**
* Destroy the React component.
*/
destroy(): void {
this.destroyed = true
const editor = this.editor as EditorWithContentComponent
editor?.contentComponent?.removeRenderer(this.id)
// If the consumer appended the element to the document (for example
// many demos append the renderer element to document.body), make sure
// we remove it here to avoid leaking DOM nodes / React roots.
try {
if (this.element && this.element.parentNode) {
this.element.parentNode.removeChild(this.element)
}
} catch {
// ignore DOM removal errors
}
}
/**
* Update the attributes of the element that holds the React component.
*/
updateAttributes(attributes: Record<string, string>): void {
Object.keys(attributes).forEach(key => {
this.element.setAttribute(key, attributes[key])
})
}
}
+224
View File
@@ -0,0 +1,224 @@
import type { ReactNode } from 'react'
import { createContext, useContext, useMemo } from 'react'
import { EditorContext } from './Context.js'
import type { Editor, EditorContentProps, EditorStateSnapshot } from './index.js'
import { EditorContent, useEditorState } from './index.js'
/**
* The shape of the React context used by the `<Tiptap />` components.
*
* The editor instance is always available when using the default `useEditor`
* configuration. For SSR scenarios where `immediatelyRender: false` is used,
* consider using the legacy `EditorProvider` pattern instead.
*/
export type TiptapContextType = {
/** The Tiptap editor instance. */
editor: Editor
}
/**
* React context that stores the current editor instance.
*
* Use `useTiptap()` to read from this context in child components.
*/
export const TiptapContext = createContext<TiptapContextType>({
get editor(): Editor {
throw new Error('useTiptap must be used within a <Tiptap> provider')
},
})
TiptapContext.displayName = 'TiptapContext'
/**
* Hook to read the Tiptap context and access the editor instance.
*
* This is a small convenience wrapper around `useContext(TiptapContext)`.
* The editor is always available when used within a `<Tiptap>` provider.
*
* @returns The current `TiptapContextType` value from the provider.
*
* @example
* ```tsx
* import { useTiptap } from '@tiptap/react'
*
* function Toolbar() {
* const { editor } = useTiptap()
*
* return (
* <button onClick={() => editor.chain().focus().toggleBold().run()}>
* Bold
* </button>
* )
* }
* ```
*/
export const useTiptap = () => useContext(TiptapContext)
/**
* Select a slice of the editor state using the context-provided editor.
*
* This is a thin wrapper around `useEditorState` that reads the `editor`
* instance from `useTiptap()` so callers don't have to pass it manually.
*
* @typeParam TSelectorResult - The type returned by the selector.
* @param selector - Function that receives the editor state snapshot and
* returns the piece of state you want to subscribe to.
* @param equalityFn - Optional function to compare previous/next selected
* values and avoid unnecessary updates.
* @returns The selected slice of the editor state.
*
* @example
* ```tsx
* function WordCount() {
* const wordCount = useTiptapState(state => {
* const text = state.editor.state.doc.textContent
* return text.split(/\s+/).filter(Boolean).length
* })
*
* return <span>{wordCount} words</span>
* }
* ```
*/
export function useTiptapState<TSelectorResult>(
selector: (context: EditorStateSnapshot<Editor>) => TSelectorResult,
equalityFn?: (a: TSelectorResult, b: TSelectorResult | null) => boolean,
) {
const { editor } = useTiptap()
return useEditorState({
editor,
selector,
equalityFn,
})
}
/**
* Props for the `Tiptap` root/provider component.
*/
export type TiptapWrapperProps = {
/**
* The editor instance to provide to child components.
* Use `useEditor()` to create this instance.
*/
editor?: Editor
/**
* @deprecated Use `editor` instead. Will be removed in the next major version.
*/
instance?: Editor
children: ReactNode
}
/**
* Top-level provider component that makes the editor instance available via
* React context to all child components.
*
* This component also provides backwards compatibility with the legacy
* `EditorContext`, so components using `useCurrentEditor()` will work
* inside a `<Tiptap>` provider.
*
* @param props - Component props.
* @returns A context provider element wrapping `children`.
*
* @example
* ```tsx
* import { Tiptap, useEditor } from '@tiptap/react'
*
* function App() {
* const editor = useEditor({ extensions: [...] })
*
* return (
* <Tiptap editor={editor}>
* <Toolbar />
* <Tiptap.Content />
* </Tiptap>
* )
* }
* ```
*/
export function TiptapWrapper({ editor, instance, children }: TiptapWrapperProps) {
const resolvedEditor = editor ?? instance
if (!resolvedEditor) {
throw new Error('Tiptap: An editor instance is required. Pass a non-null `editor` prop.')
}
const tiptapContextValue = useMemo<TiptapContextType>(() => ({ editor: resolvedEditor }), [resolvedEditor])
// Provide backwards compatibility with the legacy EditorContext
// so components using useCurrentEditor() work inside <Tiptap>
const legacyContextValue = useMemo(() => ({ editor: resolvedEditor }), [resolvedEditor])
return (
<EditorContext.Provider value={legacyContextValue}>
<TiptapContext.Provider value={tiptapContextValue}>{children}</TiptapContext.Provider>
</EditorContext.Provider>
)
}
TiptapWrapper.displayName = 'Tiptap'
/**
* Convenience component that renders `EditorContent` using the context-provided
* editor instance. Use this instead of manually passing the `editor` prop.
*
* @param props - All `EditorContent` props except `editor` and `ref`.
* @returns An `EditorContent` element bound to the context editor.
*
* @example
* ```tsx
* // inside a Tiptap provider
* <Tiptap.Content className="editor" />
* ```
*/
export function TiptapContent({ ...rest }: Omit<EditorContentProps, 'editor' | 'ref'>) {
const { editor } = useTiptap()
return <EditorContent editor={editor} {...rest} />
}
TiptapContent.displayName = 'Tiptap.Content'
/**
* Root `Tiptap` component. Use it as the provider for all child components.
*
* The exported object includes the `Content` subcomponent for rendering the
* editor content area.
*
* This component provides both the new `TiptapContext` (accessed via `useTiptap()`)
* and the legacy `EditorContext` (accessed via `useCurrentEditor()`) for
* backwards compatibility.
*
* For bubble menus and floating menus, import them separately from
* `@tiptap/react/menus` to keep floating-ui as an optional dependency.
*
* @example
* ```tsx
* import { Tiptap, useEditor } from '@tiptap/react'
* import { BubbleMenu } from '@tiptap/react/menus'
*
* function App() {
* const editor = useEditor({ extensions: [...] })
*
* return (
* <Tiptap editor={editor}>
* <Tiptap.Content />
* <BubbleMenu>
* <button onClick={() => editor.chain().focus().toggleBold().run()}>Bold</button>
* </BubbleMenu>
* </Tiptap>
* )
* }
* ```
*/
export const Tiptap = Object.assign(TiptapWrapper, {
/**
* The Tiptap Content component that renders the EditorContent with the editor instance from the context.
* @see TiptapContent
*/
Content: TiptapContent,
})
export default Tiptap
+13
View File
@@ -0,0 +1,13 @@
export * from './Context.js'
export * from './EditorContent.js'
export * from './NodeViewContent.js'
export * from './NodeViewWrapper.js'
export * from './ReactMarkViewRenderer.js'
export * from './ReactNodeViewRenderer.js'
export * from './ReactRenderer.js'
export * from './Tiptap.js'
export * from './types.js'
export * from './useEditor.js'
export * from './useEditorState.js'
export * from './useReactNodeView.js'
export * from '@tiptap/core'
+145
View File
@@ -0,0 +1,145 @@
import { type BubbleMenuPluginProps, BubbleMenuPlugin } from '@tiptap/extension-bubble-menu'
import { useCurrentEditor } from '@tiptap/react'
import React, { useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>
export type BubbleMenuProps = Optional<Omit<Optional<BubbleMenuPluginProps, 'pluginKey'>, 'element'>, 'editor'> &
React.HTMLAttributes<HTMLDivElement>
export const BubbleMenu = React.forwardRef<HTMLDivElement, BubbleMenuProps>(
(
{
pluginKey = 'bubbleMenu',
editor,
updateDelay,
resizeDelay,
appendTo,
shouldShow = null,
getReferencedVirtualElement,
options,
children,
...restProps
},
ref,
) => {
const menuEl = useRef(document.createElement('div'))
if (typeof ref === 'function') {
ref(menuEl.current)
} else if (ref) {
ref.current = menuEl.current
}
const { editor: currentEditor } = useCurrentEditor()
/**
* The editor instance where the bubble menu plugin will be registered.
*/
const pluginEditor = editor || currentEditor
// Creating a useMemo would be more computationally expensive than just
// re-creating this object on every render.
const bubbleMenuPluginProps: Omit<BubbleMenuPluginProps, 'editor' | 'element'> = {
updateDelay,
resizeDelay,
appendTo,
pluginKey,
shouldShow,
getReferencedVirtualElement,
options,
}
/**
* The props for the bubble menu plugin. They are accessed inside a ref to
* avoid running the useEffect hook and re-registering the plugin when the
* props change.
*/
const bubbleMenuPluginPropsRef = useRef(bubbleMenuPluginProps)
bubbleMenuPluginPropsRef.current = bubbleMenuPluginProps
/**
* Track whether the plugin has been initialized, so we only send updates
* after the initial registration.
*/
const [pluginInitialized, setPluginInitialized] = useState(false)
/**
* Track whether we need to skip the first options update dispatch.
* This prevents unnecessary updates right after plugin initialization.
*/
const skipFirstUpdateRef = useRef(true)
useEffect(() => {
if (pluginEditor?.isDestroyed) {
return
}
if (!pluginEditor) {
console.warn('BubbleMenu component is not rendered inside of an editor component or does not have editor prop.')
return
}
const bubbleMenuElement = menuEl.current
bubbleMenuElement.style.visibility = 'hidden'
bubbleMenuElement.style.position = 'absolute'
const plugin = BubbleMenuPlugin({
...bubbleMenuPluginPropsRef.current,
editor: pluginEditor,
element: bubbleMenuElement,
})
pluginEditor.registerPlugin(plugin)
const createdPluginKey = bubbleMenuPluginPropsRef.current.pluginKey
skipFirstUpdateRef.current = true
setPluginInitialized(true)
return () => {
setPluginInitialized(false)
pluginEditor.unregisterPlugin(createdPluginKey)
window.requestAnimationFrame(() => {
if (bubbleMenuElement.parentNode) {
bubbleMenuElement.parentNode.removeChild(bubbleMenuElement)
}
})
}
}, [pluginEditor])
/**
* Update the plugin options when props change after the plugin has been initialized.
* This allows dynamic updates to options like scrollTarget without re-registering the entire plugin.
*/
useEffect(() => {
if (!pluginInitialized || !pluginEditor || pluginEditor.isDestroyed) {
return
}
// Skip the first update right after initialization since the plugin was just created with these options
if (skipFirstUpdateRef.current) {
skipFirstUpdateRef.current = false
return
}
pluginEditor.view.dispatch(
pluginEditor.state.tr.setMeta('bubbleMenu', {
type: 'updateOptions',
options: bubbleMenuPluginPropsRef.current,
}),
)
}, [
pluginInitialized,
pluginEditor,
updateDelay,
resizeDelay,
shouldShow,
options,
appendTo,
getReferencedVirtualElement,
])
return createPortal(<div {...restProps}>{children}</div>, menuEl.current)
},
)
+140
View File
@@ -0,0 +1,140 @@
import type { FloatingMenuPluginProps } from '@tiptap/extension-floating-menu'
import { FloatingMenuPlugin } from '@tiptap/extension-floating-menu'
import { useCurrentEditor } from '@tiptap/react'
import React, { useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>
export type FloatingMenuProps = Omit<Optional<FloatingMenuPluginProps, 'pluginKey'>, 'element' | 'editor'> & {
editor: FloatingMenuPluginProps['editor'] | null
options?: FloatingMenuPluginProps['options']
} & React.HTMLAttributes<HTMLDivElement>
export const FloatingMenu = React.forwardRef<HTMLDivElement, FloatingMenuProps>(
(
{
pluginKey = 'floatingMenu',
editor,
updateDelay,
resizeDelay,
appendTo,
shouldShow = null,
options,
children,
...restProps
},
ref,
) => {
const menuEl = useRef(document.createElement('div'))
if (typeof ref === 'function') {
ref(menuEl.current)
} else if (ref) {
ref.current = menuEl.current
}
const { editor: currentEditor } = useCurrentEditor()
/**
* The editor instance where the floating menu plugin will be registered.
*/
const pluginEditor = editor || currentEditor
// Creating a useMemo would be more computationally expensive than just
// re-creating this object on every render.
const floatingMenuPluginProps: Omit<FloatingMenuPluginProps, 'editor' | 'element'> = {
updateDelay,
resizeDelay,
appendTo,
pluginKey,
shouldShow,
options,
}
/**
* The props for the floating menu plugin. They are accessed inside a ref to
* avoid running the useEffect hook and re-registering the plugin when the
* props change.
*/
const floatingMenuPluginPropsRef = useRef(floatingMenuPluginProps)
floatingMenuPluginPropsRef.current = floatingMenuPluginProps
/**
* Track whether the plugin has been initialized, so we only send updates
* after the initial registration.
*/
const [pluginInitialized, setPluginInitialized] = useState(false)
/**
* Track whether we need to skip the first options update dispatch.
* This prevents unnecessary updates right after plugin initialization.
*/
const skipFirstUpdateRef = useRef(true)
useEffect(() => {
if (pluginEditor?.isDestroyed) {
return
}
if (!pluginEditor) {
console.warn(
'FloatingMenu component is not rendered inside of an editor component or does not have editor prop.',
)
return
}
const floatingMenuElement = menuEl.current
floatingMenuElement.style.visibility = 'hidden'
floatingMenuElement.style.position = 'absolute'
const plugin = FloatingMenuPlugin({
...floatingMenuPluginPropsRef.current,
editor: pluginEditor,
element: floatingMenuElement,
})
pluginEditor.registerPlugin(plugin)
const createdPluginKey = floatingMenuPluginPropsRef.current.pluginKey
skipFirstUpdateRef.current = true
setPluginInitialized(true)
return () => {
setPluginInitialized(false)
pluginEditor.unregisterPlugin(createdPluginKey)
window.requestAnimationFrame(() => {
if (floatingMenuElement.parentNode) {
floatingMenuElement.parentNode.removeChild(floatingMenuElement)
}
})
}
}, [pluginEditor])
/**
* Update the plugin options when props change after the plugin has been initialized.
* This allows dynamic updates to options like scrollTarget without re-registering the entire plugin.
*/
useEffect(() => {
if (!pluginInitialized || !pluginEditor || pluginEditor.isDestroyed) {
return
}
// Skip the first update right after initialization since the plugin was just created with these options
if (skipFirstUpdateRef.current) {
skipFirstUpdateRef.current = false
return
}
pluginEditor.view.dispatch(
pluginEditor.state.tr.setMeta('floatingMenu', {
type: 'updateOptions',
options: floatingMenuPluginPropsRef.current,
}),
)
}, [pluginInitialized, pluginEditor, updateDelay, resizeDelay, shouldShow, options, appendTo])
return createPortal(<div {...restProps}>{children}</div>, menuEl.current)
},
)
+2
View File
@@ -0,0 +1,2 @@
export * from './BubbleMenu.js'
export * from './FloatingMenu.js'
+6
View File
@@ -0,0 +1,6 @@
import type { NodeViewProps as CoreNodeViewProps } from '@tiptap/core'
import type React from 'react'
export type ReactNodeViewProps<T = HTMLElement> = CoreNodeViewProps & {
ref: React.RefObject<T | null>
}
+382
View File
@@ -0,0 +1,382 @@
import { type EditorOptions, Editor } from '@tiptap/core'
import type { DependencyList, MutableRefObject } from 'react'
import { useDebugValue, useEffect, useRef, useState } from 'react'
import { useSyncExternalStore } from 'use-sync-external-store/shim/index.js'
import { useEditorState } from './useEditorState.js'
// @ts-ignore
const isDev = process.env.NODE_ENV !== 'production'
const isSSR = typeof window === 'undefined'
const isNext = isSSR || Boolean(typeof window !== 'undefined' && (window as any).next)
/**
* The options for the `useEditor` hook.
*/
export type UseEditorOptions = Partial<EditorOptions> & {
/**
* Whether to render the editor on the first render.
* If client-side rendering, set this to `true`.
* If server-side rendering, set this to `false`.
* @default true
*/
immediatelyRender?: boolean
/**
* Whether to re-render the editor on each transaction.
* This is legacy behavior that will be removed in future versions.
* @default false
*/
shouldRerenderOnTransaction?: boolean
}
/**
* This class handles the creation, destruction, and re-creation of the editor instance.
*/
class EditorInstanceManager {
/**
* The current editor instance.
*/
private editor: Editor | null = null
/**
* The most recent options to apply to the editor.
*/
private options: MutableRefObject<UseEditorOptions>
/**
* The subscriptions to notify when the editor instance
* has been created or destroyed.
*/
private subscriptions = new Set<() => void>()
/**
* A timeout to destroy the editor if it was not mounted within a time frame.
*/
private scheduledDestructionTimeout: ReturnType<typeof setTimeout> | undefined
/**
* Whether the editor has been mounted.
*/
private isComponentMounted = false
/**
* The most recent dependencies array.
*/
private previousDeps: DependencyList | null = null
/**
* The unique instance ID. This is used to identify the editor instance. And will be re-generated for each new instance.
*/
public instanceId = ''
constructor(options: MutableRefObject<UseEditorOptions>) {
this.options = options
this.subscriptions = new Set<() => void>()
this.setEditor(this.getInitialEditor())
this.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)
}
private setEditor(editor: Editor | null) {
this.editor = editor
this.instanceId = Math.random().toString(36).slice(2, 9)
// Notify all subscribers that the editor instance has been created
this.subscriptions.forEach(cb => cb())
}
private getInitialEditor() {
if (this.options.current.immediatelyRender === undefined) {
if (isSSR || isNext) {
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.
*/
throw new Error(
'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.
*/
private createEditor(): Editor {
const optionsToApply: Partial<EditorOptions> = {
...this.options.current,
// Always call the most recent version of the callback function by default
onBeforeCreate: (...args) => this.options.current.onBeforeCreate?.(...args),
onBlur: (...args) => this.options.current.onBlur?.(...args),
onCreate: (...args) => this.options.current.onCreate?.(...args),
onDestroy: (...args) => this.options.current.onDestroy?.(...args),
onFocus: (...args) => this.options.current.onFocus?.(...args),
onSelectionUpdate: (...args) => this.options.current.onSelectionUpdate?.(...args),
onTransaction: (...args) => this.options.current.onTransaction?.(...args),
onUpdate: (...args) => this.options.current.onUpdate?.(...args),
onContentError: (...args) => this.options.current.onContentError?.(...args),
onDrop: (...args) => this.options.current.onDrop?.(...args),
onPaste: (...args) => this.options.current.onPaste?.(...args),
onDelete: (...args) => this.options.current.onDelete?.(...args),
}
const editor = new 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(): Editor | null {
return this.editor
}
/**
* Always disable the editor on the server-side.
*/
getServerSnapshot(): null {
return null
}
/**
* Subscribe to the editor instance's changes.
*/
subscribe(onStoreChange: () => void) {
this.subscriptions.add(onStoreChange)
return () => {
this.subscriptions.delete(onStoreChange)
}
}
static compareOptions(a: UseEditorOptions, b: UseEditorOptions) {
return (Object.keys(a) as (keyof UseEditorOptions)[]).every(key => {
if (
[
'onCreate',
'onBeforeCreate',
'onDestroy',
'onUpdate',
'onTransaction',
'onFocus',
'onBlur',
'onSelectionUpdate',
'onContentError',
'onDrop',
'onPaste',
].includes(key)
) {
// we don't want to compare callbacks, they are always different and only registered once
return true
}
// We often encourage putting extensions inlined in the options object, so we will do a slightly deeper comparison here
if (key === 'extensions' && a.extensions && b.extensions) {
if (a.extensions.length !== b.extensions.length) {
return false
}
return a.extensions.every((extension, index) => {
if (extension !== b.extensions?.[index]) {
return false
}
return true
})
}
if (a[key] !== b[key]) {
// if any of the options have changed, we should update the editor options
return false
}
return true
})
}
/**
* On each render, we will create, update, or destroy the editor instance.
* @param deps The dependencies to watch for changes
* @returns A cleanup function
*/
onRender(deps: DependencyList) {
// The returned callback will run on each render
return () => {
this.isComponentMounted = true
// Cleanup any scheduled destructions, since we are currently rendering
clearTimeout(this.scheduledDestructionTimeout)
if (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 generally
if (!EditorInstanceManager.compareOptions(this.options.current, this.editor.options)) {
// But, the options are different, so we need to update the editor options
// Still, this is faster than re-creating the editor
this.editor.setOptions({
...this.options.current,
editable: this.editor.isEditable,
})
}
} 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.
*/
private refreshEditorInstance(deps: DependencyList) {
if (this.editor && !this.editor.isDestroyed) {
// Editor instance already exists
if (this.previousDeps === null) {
// If lastDeps has not yet been initialized, reuse the current editor instance
this.previousDeps = deps
return
}
const depsAreEqual =
this.previousDeps.length === deps.length && this.previousDeps.every((dep, index) => dep === deps[index])
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.
*/
private 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)
}
}
/**
* This hook allows you to create an editor instance.
* @param options The editor options
* @param deps The dependencies to watch for changes
* @returns The editor instance
* @example const editor = useEditor({ extensions: [...] })
*/
export function useEditor(
options: UseEditorOptions & { immediatelyRender: false },
deps?: DependencyList,
): Editor | null
/**
* This hook allows you to create an editor instance.
* @param options The editor options
* @param deps The dependencies to watch for changes
* @returns The editor instance
* @example const editor = useEditor({ extensions: [...] })
*/
export function useEditor(options: UseEditorOptions, deps?: DependencyList): Editor
export function useEditor(options: UseEditorOptions = {}, deps: DependencyList = []): Editor | null {
const mostRecentOptions = useRef(options)
mostRecentOptions.current = options
const [instanceManager] = useState(() => new EditorInstanceManager(mostRecentOptions))
const editor = useSyncExternalStore(
instanceManager.subscribe,
instanceManager.getEditor,
instanceManager.getServerSnapshot,
)
useDebugValue(editor)
// This effect will handle creating/updating the editor instance
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(instanceManager.onRender(deps))
// The default behavior is to re-render on each transaction
// This is legacy behavior that will be removed in future versions
useEditorState({
editor,
selector: ({ transactionNumber }) => {
if (options.shouldRerenderOnTransaction === false || options.shouldRerenderOnTransaction === undefined) {
// 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
}
+173
View File
@@ -0,0 +1,173 @@
import type { Editor } from '@tiptap/core'
import { deepEqual } from 'fast-equals'
import { useDebugValue, useEffect, useLayoutEffect, useState } from 'react'
import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector.js'
const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect
export type EditorStateSnapshot<TEditor extends Editor | null = Editor | null> = {
editor: TEditor
transactionNumber: number
}
export type UseEditorStateOptions<TSelectorResult, TEditor extends Editor | null = Editor | null> = {
/**
* The editor instance.
*/
editor: TEditor
/**
* A selector function to determine the value to compare for re-rendering.
*/
selector: (context: EditorStateSnapshot<TEditor>) => TSelectorResult
/**
* A custom equality function to determine if the editor should re-render.
* @default `deepEqual` from `fast-deep-equal`
*/
equalityFn?: (a: TSelectorResult, b: TSelectorResult | null) => boolean
}
/**
* 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<TEditor extends Editor | null = Editor | null> {
private transactionNumber = 0
private lastTransactionNumber = 0
private lastSnapshot: EditorStateSnapshot<TEditor>
private editor: TEditor
private subscribers = new Set<() => void>()
constructor(initialEditor: TEditor) {
this.editor = initialEditor
this.lastSnapshot = { editor: initialEditor, transactionNumber: 0 }
this.getSnapshot = this.getSnapshot.bind(this)
this.getServerSnapshot = this.getServerSnapshot.bind(this)
this.watch = this.watch.bind(this)
this.subscribe = this.subscribe.bind(this)
}
/**
* Get the current editor instance.
*/
getSnapshot(): EditorStateSnapshot<TEditor> {
if (this.transactionNumber === this.lastTransactionNumber) {
return this.lastSnapshot
}
this.lastTransactionNumber = this.transactionNumber
this.lastSnapshot = { editor: this.editor, transactionNumber: this.transactionNumber }
return this.lastSnapshot
}
/**
* Always disable the editor on the server-side.
*/
getServerSnapshot(): EditorStateSnapshot<null> {
return { editor: null, transactionNumber: 0 }
}
/**
* Subscribe to the editor instance's changes.
*/
subscribe(callback: () => void): () => void {
this.subscribers.add(callback)
return () => {
this.subscribers.delete(callback)
}
}
/**
* Watch the editor instance for changes.
*/
watch(nextEditor: Editor | null): undefined | (() => void) {
this.editor = nextEditor as TEditor
if (this.editor) {
/**
* This will force a re-render when the editor state changes.
* This is to support things like `editor.can().toggleBold()` in components that `useEditor`.
* This could be more efficient, but it's a good trade-off for now.
*/
const fn = () => {
this.transactionNumber += 1
this.subscribers.forEach(callback => callback())
}
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 }),
* })
*/
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>(
options: UseEditorStateOptions<TSelectorResult, Editor | null>,
): TSelectorResult | 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 [editorStateManager] = useState(() => new EditorStateManager(options.editor))
// Using the `useSyncExternalStore` hook to sync the editor instance with the component state
const selectedState = useSyncExternalStoreWithSelector(
editorStateManager.subscribe,
editorStateManager.getSnapshot,
editorStateManager.getServerSnapshot,
options.selector as UseEditorStateOptions<TSelectorResult, Editor | null>['selector'],
options.equalityFn ?? deepEqual,
)
useIsomorphicLayoutEffect(() => {
return editorStateManager.watch(options.editor)
}, [options.editor, editorStateManager])
useDebugValue(selectedState)
return selectedState
}
+28
View File
@@ -0,0 +1,28 @@
import type { ReactNode } from 'react'
import { createContext, createElement, useContext } from 'react'
export interface ReactNodeViewContextProps {
onDragStart?: (event: DragEvent) => void
nodeViewContentRef?: (element: HTMLElement | null) => void
/**
* This allows you to add children into the NodeViewContent component.
* This is useful when statically rendering the content of a node view.
*/
nodeViewContentChildren?: ReactNode
}
export const ReactNodeViewContext = createContext<ReactNodeViewContextProps>({
onDragStart: () => {
// no-op
},
nodeViewContentChildren: undefined,
nodeViewContentRef: () => {
// no-op
},
})
export const ReactNodeViewContentProvider = ({ children, content }: { children: ReactNode; content: ReactNode }) => {
return createElement(ReactNodeViewContext.Provider, { value: { nodeViewContentChildren: content } }, children)
}
export const useReactNodeView = () => useContext(ReactNodeViewContext)