A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
editor: fix react node views for react 18
Abdullah Atta6e5493f1498a
diff --git a/packages/editor/src/extensions/attachment/attachment.ts b/packages/editor/src/extensions/attachment/attachment.tsindex 5b5fa3b5b..dc0cb9802 100644--- a/packages/editor/src/extensions/attachment/attachment.ts+++ b/packages/editor/src/extensions/attachment/attachment.ts@@ -19,7 +19,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.import { Node, mergeAttributes, findChildren } from "@tiptap/core";import { Attribute } from "@tiptap/core";-import { createSelectionBasedNodeView } from "../react";+import { createNodeView } from "../react";import { AttachmentComponent } from "./component";import { Attachment } from "./types";@@ -96,7 +96,7 @@ export const AttachmentNode = Node.create<AttachmentOptions>({},addNodeView() {- return createSelectionBasedNodeView(AttachmentComponent, {+ return createNodeView(AttachmentComponent, {shouldUpdate: ({ attrs: prev }, { attrs: next }) => {return prev.progress !== next.progress;},diff --git a/packages/editor/src/extensions/attachment/component.tsx b/packages/editor/src/extensions/attachment/component.tsxindex d021e2ec5..17c9e1728 100644--- a/packages/editor/src/extensions/attachment/component.tsx+++ b/packages/editor/src/extensions/attachment/component.tsx@@ -22,13 +22,11 @@ import { FileAttachment } from "./types";import { useRef, useState } from "react";import { Icon } from "@notesnook/ui";import { Icons } from "../../toolbar/icons";-import { SelectionBasedReactNodeViewProps } from "../react";+import { ReactNodeViewProps } from "../react";import { ToolbarGroup } from "../../toolbar/components/toolbar-group";import { DesktopOnly } from "../../components/responsive";-export function AttachmentComponent(- props: SelectionBasedReactNodeViewProps<FileAttachment>-) {+export function AttachmentComponent(props: ReactNodeViewProps<FileAttachment>) {const { editor, node, selected } = props;const { filename, size, progress } = node.attrs;const elementRef = useRef<HTMLSpanElement>();diff --git a/packages/editor/src/extensions/code-block/code-block.ts b/packages/editor/src/extensions/code-block/code-block.tsindex da10eac53..01404bc7c 100644--- a/packages/editor/src/extensions/code-block/code-block.ts+++ b/packages/editor/src/extensions/code-block/code-block.ts@@ -597,10 +597,10 @@ function indentOnEnter(editor: Editor, $from: ResolvedPos, options: Indent) {return editor.chain()- .insertContent(`${newline}${indentation}`, {+ .newlineInCode()+ .insertContent(`${indentation}`, {parseOptions: { preserveWhitespace: true }})- .focus().run();}diff --git a/packages/editor/src/extensions/embed/component.tsx b/packages/editor/src/extensions/embed/component.tsxindex 840592d00..9f8a520c7 100644--- a/packages/editor/src/extensions/embed/component.tsx+++ b/packages/editor/src/extensions/embed/component.tsx@@ -20,7 +20,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.import { Box, Flex, Embed } from "@theme-ui/components";import { useRef, useState } from "react";import { EmbedAlignmentOptions, EmbedAttributes } from "./embed";-import { SelectionBasedReactNodeViewProps } from "../react";+import { ReactNodeViewProps } from "../react";import { DesktopOnly } from "../../components/responsive";import { ToolbarGroup } from "../../toolbar/components/toolbar-group";import { Icons } from "../../toolbar";@@ -28,9 +28,7 @@ import { Icon } from "@notesnook/ui";import { Resizer } from "../../components/resizer";export function EmbedComponent(- props: SelectionBasedReactNodeViewProps<- EmbedAttributes & EmbedAlignmentOptions- >+ props: ReactNodeViewProps<EmbedAttributes & EmbedAlignmentOptions>) {const { editor, updateAttributes, selected, node } = props;const [isLoading, setIsLoading] = useState(true);diff --git a/packages/editor/src/extensions/embed/embed.ts b/packages/editor/src/extensions/embed/embed.tsindex 4490ec51c..436aea4f3 100644--- a/packages/editor/src/extensions/embed/embed.ts+++ b/packages/editor/src/extensions/embed/embed.ts@@ -19,7 +19,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.import { Node, mergeAttributes } from "@tiptap/core";import { hasSameAttributes } from "../../utils/prosemirror";-import { createSelectionBasedNodeView } from "../react";+import { createNodeView } from "../react";import { TextDirections } from "../text-direction";import { EmbedComponent } from "./component";@@ -101,7 +101,7 @@ export const EmbedNode = Node.create<EmbedOptions>({},addNodeView() {- return createSelectionBasedNodeView(EmbedComponent, {+ return createNodeView(EmbedComponent, {shouldUpdate: (prev, next) => !hasSameAttributes(prev.attrs, next.attrs)});},diff --git a/packages/editor/src/extensions/image/component.tsx b/packages/editor/src/extensions/image/component.tsxindex 1167eed13..4cb4b9955 100644--- a/packages/editor/src/extensions/image/component.tsx+++ b/packages/editor/src/extensions/image/component.tsx@@ -21,7 +21,7 @@ import { ThemeUIStyleObject } from "@theme-ui/core";import { Box, Flex, Image, Text } from "@theme-ui/components";import { ImageAttributes } from "./image";import { useEffect, useState } from "react";-import { SelectionBasedReactNodeViewProps } from "../react";+import { ReactNodeViewProps } from "../react";import { DesktopOnly } from "../../components/responsive";import { Icon } from "@notesnook/ui";import { Icons } from "../../toolbar/icons";@@ -46,7 +46,7 @@ import DataURL from "@notesnook/core/dist/utils/dataurl";export const AnimatedImage = motion(Image);export function ImageComponent(- props: SelectionBasedReactNodeViewProps<Partial<ImageAttributes>>+ props: ReactNodeViewProps<Partial<ImageAttributes>>) {const { editor, node, selected } = props;const { src, alt, title, textDirection, hash, aspectRatio, mime, progress } =diff --git a/packages/editor/src/extensions/image/image.ts b/packages/editor/src/extensions/image/image.tsindex addb80965..7317f2986 100644--- a/packages/editor/src/extensions/image/image.ts+++ b/packages/editor/src/extensions/image/image.ts@@ -24,7 +24,7 @@ import {ImageAttachment,getDataAttribute} from "../attachment";-import { createSelectionBasedNodeView } from "../react";+import { createNodeView } from "../react";import { TextDirections } from "../text-direction";import { ImageComponent } from "./component";@@ -136,7 +136,7 @@ export const ImageNode = Node.create<ImageOptions>({},addNodeView() {- return createSelectionBasedNodeView(ImageComponent, {+ return createNodeView(ImageComponent, {componentKey: (node) => node.attrs.hash,shouldUpdate: (prev, next) => !hasSameAttributes(prev.attrs, next.attrs),forceEnableSelection: truediff --git a/packages/editor/src/extensions/react/event-dispatcher.ts b/packages/editor/src/extensions/react/event-dispatcher.tsindex 3bef27e9b..4fcac3807 100644--- a/packages/editor/src/extensions/react/event-dispatcher.ts+++ b/packages/editor/src/extensions/react/event-dispatcher.ts@@ -61,23 +61,3 @@ export class EventDispatcher<T = never> {this.listeners = {};}}--/**- * Creates a dispatch function that can be called inside ProseMirror Plugin- * to notify listeners about that plugin's state change.- */-export function createDispatch<T>(- eventDispatcher: EventDispatcher<T>-): Dispatch<T> {- return (eventName: PluginKey | string, data: T) => {- if (!eventName) {- throw new Error("event name is required!");- }-- const event =- typeof eventName === "string"- ? eventName- : (eventName as PluginKey & { key: string }).key;- eventDispatcher.emit(event, data);- };-}diff --git a/packages/editor/src/extensions/react/index.ts b/packages/editor/src/extensions/react/index.tsindex 8a8baea16..f0e78cdbf 100644--- a/packages/editor/src/extensions/react/index.ts+++ b/packages/editor/src/extensions/react/index.ts@@ -20,6 +20,4 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.export * from "./react-node-view";export * from "./types";export * from "./react-portal-provider";-export * from "./selection-based-react-node-view";-export * from "./plugin";export * from "./event-dispatcher";diff --git a/packages/editor/src/extensions/react/plugin.ts b/packages/editor/src/extensions/react/plugin.tsdeleted file mode 100644index 067e9b001..000000000--- a/packages/editor/src/extensions/react/plugin.ts+++ /dev/null@@ -1,75 +0,0 @@-/*-This file is part of the Notesnook project (https://notesnook.com/)--Copyright (C) 2023 Streetwriters (Private) Limited--This program is free software: you can redistribute it and/or modify-it under the terms of the GNU General Public License as published by-the Free Software Foundation, either version 3 of the License, or-(at your option) any later version.--This program is distributed in the hope that it will be useful,-but WITHOUT ANY WARRANTY; without even the implied warranty of-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-GNU General Public License for more details.--You should have received a copy of the GNU General Public License-along with this program. If not, see <http://www.gnu.org/licenses/>.-*/--import { Plugin, PluginKey } from "prosemirror-state";-import { EditorView } from "prosemirror-view";-import { Extension } from "@tiptap/core";--export type StateChangeHandler = (fromPos: number, toPos: number) => void;--export class ReactNodeViewState {- private changeHandlers: StateChangeHandler[] = [];-- constructor() {- this.changeHandlers = [];- }-- subscribe(cb: StateChangeHandler) {- this.changeHandlers.push(cb);- }-- unsubscribe(cb: StateChangeHandler) {- this.changeHandlers = this.changeHandlers.filter((ch) => ch !== cb);- }-- notifyNewSelection(fromPos: number, toPos: number) {- this.changeHandlers.forEach((cb) => cb(fromPos, toPos));- }-}--export const stateKey = new PluginKey("reactNodeView");--export const NodeViewSelectionNotifierPlugin = new Plugin({- state: {- init() {- return new ReactNodeViewState();- },- apply(_tr, pluginState: ReactNodeViewState) {- return pluginState;- }- },- key: stateKey,- view: (view: EditorView) => {- const pluginState: ReactNodeViewState = stateKey.getState(view.state);-- return {- update: (view: EditorView) => {- const { from, to } = view.state.selection;- pluginState.notifyNewSelection(from, to);- }- };- }-});--export const NodeViewSelectionNotifier = Extension.create({- name: "node-view-selection-notifier",- addProseMirrorPlugins() {- return [NodeViewSelectionNotifierPlugin];- }-});diff --git a/packages/editor/src/extensions/react/react-node-view.tsx b/packages/editor/src/extensions/react/react-node-view.tsxindex adac540d4..4273ca3da 100644--- a/packages/editor/src/extensions/react/react-node-view.tsx+++ b/packages/editor/src/extensions/react/react-node-view.tsx@@ -17,7 +17,7 @@ You should have received a copy of the GNU General Public Licensealong with this program. If not, see <http://www.gnu.org/licenses/>.*/-import React, { SyntheticEvent } from "react";+import React, { FunctionComponent, SyntheticEvent } from "react";import { NodeView, Decoration, DecorationSource } from "prosemirror-view";import { Node as PMNode, Slice } from "prosemirror-model";import { NodeSelection } from "prosemirror-state";@@ -26,7 +26,6 @@ import {ReactNodeViewProps,ReactNodeViewOptions,GetPosNode,- ForwardRef,ContentDOM} from "./types";import { Editor, NodeViewRendererProps } from "@tiptap/core";@@ -50,6 +49,9 @@ export class ReactNodeView<P extends ReactNodeViewProps> implements NodeView {contentDOM: HTMLElement | undefined;node: PMNode;isDragging = false;+ selected = false;+ pos = -1;+ posEnd: number | undefined;constructor(node: PMNode,protected readonly editor: Editor,@@ -58,6 +60,17 @@ export class ReactNodeView<P extends ReactNodeViewProps> implements NodeView {protected readonly options: ReactNodeViewOptions<P>) {this.node = node;+ this.#updatePos();+ }++ deselectNode() {+ this.selected = false;+ this.render();+ }++ selectNode() {+ this.selected = true;+ this.render();}/**@@ -74,10 +87,7 @@ export class ReactNodeView<P extends ReactNodeViewProps> implements NodeView {this.domRef.ondragstart = (ev) => this.onDragStart(ev);// this.setDomAttrs(this.node, this.domRef);- const { dom: contentDOMWrapper, contentDOM } = this.getContentDOM() || {- dom: undefined,- contentDOM: undefined- };+ const { dom: contentDOMWrapper, contentDOM } = this.getContentDOM() ?? {};if (this.domRef && contentDOMWrapper) {this.domRef.appendChild(contentDOMWrapper);@@ -90,24 +100,19 @@ export class ReactNodeView<P extends ReactNodeViewProps> implements NodeView {// nodeView if DOM structure has nested plain "div"s, it doesn't see the// difference between them and it kills the nodeViewthis.domRef.classList.add(`${this.node.type.name}-view-content-wrap`);-- this.renderReactComponent(() =>- this.render(this.options.props, this.handleRef)- );+ this.render();return this;}- private renderReactComponent(- component: () => React.ReactElement<unknown> | null- ) {+ private render() {if (process.env.NODE_ENV === "test") return;- if (!this.domRef || !component || !this.portalProviderAPI) {+ if (!this.domRef || !this.portalProviderAPI) {console.warn("Cannot render node view");return;}- this.portalProviderAPI.render(component, this.domRef);+ this.portalProviderAPI.render(this.Component, this.domRef);}createDomRef(): HTMLElement {@@ -136,32 +141,35 @@ export class ReactNodeView<P extends ReactNodeViewProps> implements NodeView {return this.options.contentDOMFactory?.();}+ #updatePos() {+ this.pos = this.getPos();+ this.posEnd = this.pos + this.node.nodeSize;+ }+handleRef = (node: HTMLElement | null) => this._handleRef(node);- private _handleRef(node: HTMLElement | null) {+ private _handleRef = (node: HTMLElement | null) => {const contentDOM = this.contentDOMWrapper || this.contentDOM;// move the contentDOM node inside the inner reference after renderingif (node && contentDOM && !node.contains(contentDOM)) {node.appendChild(contentDOM);}- }+ };- render(- props: P = {} as P,- forwardRef?: ForwardRef- ): React.ReactElement<unknown> | null {+ Component: FunctionComponent = () => {if (!this.options.component) return null;return (<EmotionThemeProvider scope="editor" injectCssVars={false}><this.options.component- {...props}- pos={this.getPos()}+ {...(this.options.props as P)}+ pos={this.pos}editor={this.editor}getPos={this.getPos}node={this.node}- forwardRef={forwardRef}+ forwardRef={this._handleRef}+ selected={this.selected}updateAttributes={(attr, options) =>this.updateAttributes(attr,@@ -174,7 +182,7 @@ export class ReactNodeView<P extends ReactNodeViewProps> implements NodeView {/></EmotionThemeProvider>);- }+ };updateAttributes(attributes: object,@@ -221,9 +229,9 @@ export class ReactNodeView<P extends ReactNodeViewProps> implements NodeView {this.node = node;- this.renderReactComponent(() =>- this.render(this.options.props, this.handleRef)- );+ this.#updatePos();++ this.render();return true;}@@ -463,13 +471,8 @@ export class ReactNodeView<P extends ReactNodeViewProps> implements NodeView {}destroy() {- if (!this.domRef || !this.portalProviderAPI) {- return;- }-+ if (!this.portalProviderAPI) return;this.portalProviderAPI.remove(this.domRef);- // this.domRef = undefined;- this.contentDOM = undefined;}}diff --git a/packages/editor/src/extensions/react/react-portal-provider.tsx b/packages/editor/src/extensions/react/react-portal-provider.tsxindex 2129c7f30..849b28e72 100644--- a/packages/editor/src/extensions/react/react-portal-provider.tsx+++ b/packages/editor/src/extensions/react/react-portal-provider.tsx@@ -17,64 +17,73 @@ You should have received a copy of the GNU General Public Licensealong with this program. If not, see <http://www.gnu.org/licenses/>.*/-import React, { PropsWithChildren, useContext } from "react";-import { createPortal } from "react-dom";+import React, {+ FunctionComponent,+ PropsWithChildren,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState+} from "react";+import { createPortal, flushSync } from "react-dom";import { EventDispatcher } from "./event-dispatcher";-import { Root, createRoot } from "react-dom/client";+import { nanoid } from "nanoid";export type BasePortalProviderProps = PropsWithChildren<unknown>;-export type Portals = Map<HTMLElement, React.ReactChild>;+export type Portals = Map<HTMLElement, MountedPortal>;++export interface MountedPortal {+ key: string;+ Component: FunctionComponent;+}export type PortalRendererState = {portals: Portals;};-export class PortalProviderAPI extends EventDispatcher {- portals: Map<HTMLElement, Root> = new Map();- context?: PortalRenderer;+export class PortalProviderAPI extends EventDispatcher<Portals> {+ portals: Map<HTMLElement, MountedPortal> = new Map();constructor() {super();}- setContext = (context: PortalRenderer) => {- this.context = context;- };-- render(- children: () => React.ReactChild | JSX.Element | null,- container: HTMLElement,- callback?: () => void- ) {- const root = this.portals.get(container) || createRoot(container);- root.render(children());- this.portals.set(container, root);+ /**+ * Trigger an update in all subscribers.+ */+ private update() {+ this.emit("update", this.portals);}- // TODO: until https://product-fabric.atlassian.net/browse/ED-5013- // we (unfortunately) need to re-render to pass down any updated context.- // selectively do this for nodeviews that opt-in via `hasAnalyticsContext`- forceUpdate() {}+ render(Component: FunctionComponent, container: HTMLElement) {+ const portal = this.portals.get(container);+ this.portals.set(container, { Component, key: portal?.key ?? nanoid() });+ this.update();+ }++ /**+ * Force an update in all the portals by setting new keys for every portal.+ *+ * Delete all orphaned containers (deleted from the DOM). This is useful for+ * Decoration where there is no destroy method.+ */+ forceUpdate(): void {+ for (const [container, { Component }] of this.portals) {+ this.portals.set(container, { Component, key: nanoid() });+ }+ }remove(container: HTMLElement) {- const root = this.portals.get(container);+ // Remove the portal which was being wrapped in the provided container.this.portals.delete(container);- // There is a race condition that can happen caused by Prosemirror vs React,- // where Prosemirror removes the container from the DOM before React gets- // around to removing the child from the container- // This will throw a NotFoundError: The node to be removed is not a child of this node- // Both Prosemirror and React remove the elements asynchronously, and in edge- // cases Prosemirror beats React- try {- root?.unmount();- // unmountComponentAtNode(container);- } catch (error) {- // IGNORE console.error(error);- }+ // Trigger an update+ this.update();}}+const PortalProviderContext = React.createContext<PortalProviderAPI | undefined>(undefined);@@ -82,51 +91,47 @@ export function usePortalProvider() {return useContext(PortalProviderContext);}-export class PortalProvider extends React.Component<BasePortalProviderProps> {- static displayName = "PortalProvider";-- portalProviderAPI: PortalProviderAPI;+export function PortalProvider(props: PropsWithChildren) {+ const portalProviderAPI = useMemo(() => new PortalProviderAPI(), []);- constructor(props: BasePortalProviderProps) {- super(props);- this.portalProviderAPI = new PortalProviderAPI();- }-- render() {- return (- <PortalProviderContext.Provider value={this.portalProviderAPI}>- {this.props.children}- <PortalRenderer portalProviderAPI={this.portalProviderAPI} />- </PortalProviderContext.Provider>- );- }-- componentDidUpdate() {- this.portalProviderAPI.forceUpdate();- }+ return (+ <PortalProviderContext.Provider value={portalProviderAPI}>+ {props.children}+ <PortalRenderer portalProviderAPI={portalProviderAPI} />+ </PortalProviderContext.Provider>+ );}-export class PortalRenderer extends React.Component<- { portalProviderAPI: PortalProviderAPI },- PortalRendererState-> {- constructor(props: { portalProviderAPI: PortalProviderAPI }) {- super(props);- props.portalProviderAPI.setContext(this);- props.portalProviderAPI.on("update", this.handleUpdate);- this.state = { portals: new Map() };- }-- handleUpdate = (portals: Portals) => this.setState({ portals });-- render() {- const { portals } = this.state;- return (- <>- {Array.from(portals.entries()).map(([container, children]) =>- createPortal(children, container)- )}- </>- );- }+function PortalRenderer(props: { portalProviderAPI: PortalProviderAPI }) {+ const { portalProviderAPI } = props;+ const mounted = useRef(true);+ const [portals, setPortals] = useState(() =>+ Array.from(portalProviderAPI.portals.entries())+ );++ useEffect(() => {+ mounted.current = true;+ function onUpdate(portalMap: Portals) {+ // we have to make sure the component is mounted otherwise React+ // throws an error.+ if (!mounted.current) return;++ // flushSync is necessary here, otherwise we get into a loop where+ // ProseMirror destroys and recreates the node view over and over again.+ flushSync(() => setPortals(Array.from(portalMap.entries())));+ }+ portalProviderAPI.on("update", onUpdate);+ return () => {+ mounted.current = false;+ portalProviderAPI.off("update", onUpdate);+ };+ }, [portalProviderAPI]);++ return (+ <>+ {portals.map(([container, { Component, key }]) =>+ createPortal(<Component />, container, key)+ )}+ </>+ );}diff --git a/packages/editor/src/extensions/react/selection-based-react-node-view.tsx b/packages/editor/src/extensions/react/selection-based-react-node-view.tsxdeleted file mode 100644index 506e33872..000000000--- a/packages/editor/src/extensions/react/selection-based-react-node-view.tsx+++ /dev/null@@ -1,294 +0,0 @@-/*-This file is part of the Notesnook project (https://notesnook.com/)--Copyright (C) 2023 Streetwriters (Private) Limited--This program is free software: you can redistribute it and/or modify-it under the terms of the GNU General Public License as published by-the Free Software Foundation, either version 3 of the License, or-(at your option) any later version.--This program is distributed in the hope that it will be useful,-but WITHOUT ANY WARRANTY; without even the implied warranty of-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-GNU General Public License for more details.--You should have received a copy of the GNU General Public License-along with this program. If not, see <http://www.gnu.org/licenses/>.-*/--import React from "react";-import { DecorationSet } from "prosemirror-view";-import { Node as PMNode } from "prosemirror-model";-import { Selection, NodeSelection } from "prosemirror-state";-import {- stateKey as SelectionChangePluginKey,- ReactNodeViewState-} from "./plugin";-import {- ReactNodeViewOptions,- GetPosNode,- SelectionBasedReactNodeViewProps,- ForwardRef-} from "./types";-import { ReactNodeView } from "./react-node-view";-import { Editor, NodeViewRendererProps } from "@tiptap/core";-import { EmotionThemeProvider } from "@notesnook/theme";-import { PortalProviderAPI } from "./react-portal-provider";--/**- * A ReactNodeView that handles React components sensitive- * to selection changes.- *- * If the selection changes, it will attempt to re-render the- * React component. Otherwise it does nothing.- *- * You can subclass `viewShouldUpdate` to include other- * props that your component might want to consider before- * entering the React lifecycle. These are usually props you- * compare in `shouldComponentUpdate`.- *- * An example:- *- * ```- * viewShouldUpdate(nextNode) {- * if (nextNode.attrs !== this.node.attrs) {- * return true;- * }- *- * return super.viewShouldUpdate(nextNode);- * }```- */--export class SelectionBasedNodeView<- P extends SelectionBasedReactNodeViewProps-> extends ReactNodeView<P> {- private oldSelection: Selection;- private selectionChangeState: ReactNodeViewState;-- pos = -1;- posEnd: number | undefined;-- constructor(- node: PMNode,- editor: Editor,- getPos: GetPosNode,- portalProviderAPI: PortalProviderAPI,- options: ReactNodeViewOptions<P>- ) {- super(node, editor, getPos, portalProviderAPI, options);-- this.updatePos();-- this.oldSelection = editor.view.state.selection;- this.selectionChangeState = SelectionChangePluginKey.getState(- this.editor.view.state- );- this.selectionChangeState.subscribe(this.onSelectionChange);- }-- render(- props: P = {} as P,- forwardRef?: ForwardRef- ): React.ReactElement<unknown> | null {- if (!this.options.component) return null;- const isSelected =- (this.options.forceEnableSelection || this.editor.isEditable) &&- this.isSelectedNode(this.editor.view.state.selection);-- return (- <EmotionThemeProvider- key={this.options.componentKey?.(this.node)}- scope="editor"- injectCssVars={false}- >- <this.options.component- {...props}- editor={this.editor}- getPos={this.getPos}- node={this.node}- forwardRef={forwardRef}- selected={isSelected}- updateAttributes={(attr, options) =>- this.updateAttributes(- attr,- this.pos,- options?.addToHistory,- options?.preventUpdate,- options?.forceUpdate- )- }- />- </EmotionThemeProvider>- );- }-- /**- * Update current node's start and end positions.- *- * Prefer `this.pos` rather than getPos(), because calling getPos is- * expensive, unless you know you're definitely going to render.- */- private updatePos() {- if (typeof this.getPos === "boolean") {- return;- }- this.pos = this.getPos();- this.posEnd = this.pos + this.node.nodeSize;- }-- private getPositionsWithDefault(pos?: number, posEnd?: number) {- return {- pos: typeof pos !== "number" ? this.pos : pos,- posEnd: typeof posEnd !== "number" ? this.posEnd : posEnd- };- }-- isNodeInsideSelection = (- from: number,- to: number,- pos?: number,- posEnd?: number- ) => {- ({ pos, posEnd } = this.getPositionsWithDefault(pos, posEnd));-- if (typeof pos !== "number" || typeof posEnd !== "number") {- return false;- }-- return from <= pos && to >= posEnd;- };-- isSelectionInsideNode = (- from: number,- to: number,- pos?: number,- posEnd?: number- ) => {- ({ pos, posEnd } = this.getPositionsWithDefault(pos, posEnd));-- if (typeof pos !== "number" || typeof posEnd !== "number") {- return false;- }-- return pos < from && to < posEnd;- };-- private isSelectedNode = (selection: Selection): boolean => {- if (selection instanceof NodeSelection) {- const {- selection: { from, to }- } = this.editor.view.state;- return (- selection.node === this.node ||- // If nodes are not the same object, we check if they are referring to the same document node- (this.pos === from &&- this.posEnd === to &&- selection.node.eq(this.node))- );- }- return false;- };-- insideSelection = () => {- const {- selection: { from, to }- } = this.editor.view.state;-- return (- this.isSelectedNode(this.editor.view.state.selection) ||- this.isSelectionInsideNode(from, to)- );- };-- nodeInsideSelection = () => {- const { selection } = this.editor.view.state;- const { from, to } = selection;-- return (- this.isSelectedNode(selection) || this.isNodeInsideSelection(from, to)- );- };-- viewShouldUpdate(nextNode: PMNode) {- if (super.viewShouldUpdate(nextNode)) return true;-- const {- state: { selection }- } = this.editor.view;-- // update selection- const oldSelection = this.oldSelection;- this.oldSelection = selection;-- // update cached positions- const { pos: oldPos, posEnd: oldPosEnd } = this;- this.updatePos();-- const { from, to } = selection;- const { from: oldFrom, to: oldTo } = oldSelection;-- if (this.node.type.spec.selectable) {- const newNodeSelection =- selection instanceof NodeSelection && selection.from === this.pos;- const oldNodeSelection =- oldSelection instanceof NodeSelection && oldSelection.from === this.pos;-- if (- (newNodeSelection && !oldNodeSelection) ||- (oldNodeSelection && !newNodeSelection)- ) {- return true;- }- }-- const movedInToSelection =- this.isNodeInsideSelection(from, to) &&- !this.isNodeInsideSelection(oldFrom, oldTo);-- const movedOutOfSelection =- !this.isNodeInsideSelection(from, to) &&- this.isNodeInsideSelection(oldFrom, oldTo);-- const moveOutFromOldSelection =- this.isNodeInsideSelection(from, to, oldPos, oldPosEnd) &&- !this.isNodeInsideSelection(from, to);-- if (movedInToSelection || movedOutOfSelection || moveOutFromOldSelection) {- return true;- }-- return false;- }-- destroy() {- this.selectionChangeState.unsubscribe(this.onSelectionChange);- super.destroy();- }-- private onSelectionChange = () => {- this.update(this.node, [], DecorationSet.empty);- };-}--export function createSelectionBasedNodeView<- TProps extends SelectionBasedReactNodeViewProps->(- component: React.ComponentType<TProps>,- options?: Omit<ReactNodeViewOptions<TProps>, "component">-) {- return ({ node, getPos, editor }: NodeViewRendererProps) => {- const _getPos = () => (typeof getPos === "boolean" ? -1 : getPos());- if (!editor.storage.portalProviderAPI) return {};- return new SelectionBasedNodeView(- node,- editor as Editor,- _getPos,- editor.storage.portalProviderAPI,- {- ...options,- component- }- ).init();- };-}diff --git a/packages/editor/src/extensions/react/types.ts b/packages/editor/src/extensions/react/types.tsindex e365dd34e..c34279405 100644--- a/packages/editor/src/extensions/react/types.ts+++ b/packages/editor/src/extensions/react/types.ts@@ -50,13 +50,9 @@ export type ReactNodeViewProps<TAttributes = Attrs> = {editor: Editor;updateAttributes: UpdateAttributes<TAttributes>;forwardRef?: ForwardRef;+ selected: boolean;};-export type SelectionBasedReactNodeViewProps<TAttributes = Attrs> =- ReactNodeViewProps<TAttributes> & {- selected: boolean;- };-export type ReactNodeViewOptions<P> = {props?: P;component?: React.ComponentType<P>;diff --git a/packages/editor/src/extensions/web-clip/component.tsx b/packages/editor/src/extensions/web-clip/component.tsxindex ac8bfea7d..b15f42107 100644--- a/packages/editor/src/extensions/web-clip/component.tsx+++ b/packages/editor/src/extensions/web-clip/component.tsx@@ -19,7 +19,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.import { Box, Flex, Text } from "@theme-ui/components";import { useEffect, useRef, useState } from "react";-import { SelectionBasedReactNodeViewProps } from "../react";+import { ReactNodeViewProps } from "../react";import { Icons } from "../../toolbar";import { Icon } from "@notesnook/ui";import { WebClipAttributes } from "./web-clip";@@ -34,9 +34,7 @@ const FAILED_CONTENT = `<html><head></body></html>`;-export function WebClipComponent(- props: SelectionBasedReactNodeViewProps<WebClipAttributes>-) {+export function WebClipComponent(props: ReactNodeViewProps<WebClipAttributes>) {const { editor, selected, node, updateAttributes } = props;const [isLoading, setIsLoading] = useState(true);const embedRef = useRef<HTMLIFrameElement>(null);diff --git a/packages/editor/src/extensions/web-clip/web-clip.ts b/packages/editor/src/extensions/web-clip/web-clip.tsindex ac5bd4310..8aaf4196e 100644--- a/packages/editor/src/extensions/web-clip/web-clip.ts+++ b/packages/editor/src/extensions/web-clip/web-clip.ts@@ -20,7 +20,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.import { Node, mergeAttributes } from "@tiptap/core";import { hasSameAttributes } from "../../utils/prosemirror";import { WebClipAttachment, getDataAttribute } from "../attachment";-import { createSelectionBasedNodeView } from "../react";+import { createNodeView } from "../react";import { WebClipComponent } from "./component";export interface WebClipOptions {@@ -92,7 +92,7 @@ export const WebClipNode = Node.create<WebClipOptions>({},addNodeView() {- return createSelectionBasedNodeView(WebClipComponent, {+ return createNodeView(WebClipComponent, {shouldUpdate: (prev, next) => !hasSameAttributes(prev.attrs, next.attrs),forceEnableSelection: true});diff --git a/packages/editor/src/hooks/use-editor.ts b/packages/editor/src/hooks/use-editor.tsindex 6c56208aa..3d751d6c4 100644--- a/packages/editor/src/hooks/use-editor.ts+++ b/packages/editor/src/hooks/use-editor.ts@@ -103,7 +103,7 @@ export const useEditor = (editor.view.destroy();editor.destroy();};- }, []);+ }, [editor]);useEffect(() => {// this is required for the drag/drop to work properlydiff --git a/packages/editor/src/index.ts b/packages/editor/src/index.tsindex eb4e87d26..7938298d8 100644--- a/packages/editor/src/index.ts+++ b/packages/editor/src/index.ts@@ -61,11 +61,7 @@ import OrderedList from "./extensions/ordered-list";import { OutlineList } from "./extensions/outline-list";import { OutlineListItem } from "./extensions/outline-list-item";import { Paragraph } from "./extensions/paragraph";-import {- NodeViewSelectionNotifier,- PortalProviderAPI,- usePortalProvider-} from "./extensions/react";+import { PortalProviderAPI, usePortalProvider } from "./extensions/react";import { SearchReplace } from "./extensions/search-replace";import { Table } from "./extensions/table";import TableCell from "./extensions/table-cell";@@ -187,7 +183,6 @@ const useTiptap = (},extensions: [...CoreExtensions,- NodeViewSelectionNotifier,SearchReplace.configure({onStartSearch: (term) => {useEditorSearchStore.setState({