Files
Tom Moor 6e6eaf6b69 fix: Guard node view positions after the view is destroyed (#13983)
* fix: Guard node view positions after the view is destroyed

ProseMirror returns undefined from getPos once a node view is destroyed,
but ComponentProps typed it as always returning a number. Async handlers,
such as the mention unfurl, could then call setNodeMarkup with an undefined
position and throw a RangeError.

Fixes OUTLINE-CLOUD-D9N

* Remove excessive test
2026-10-07 09:09:16 -04:00

250 lines
7.3 KiB
TypeScript

import type { Node as ProsemirrorNode } from "prosemirror-model";
import type { EditorView, Decoration } from "prosemirror-view";
import type { FunctionComponent } from "react";
import type Extension from "@shared/editor/lib/Extension";
import type { ComponentProps } from "@shared/editor/types";
import type { Editor } from "~/editor";
import { NodeViewRenderer } from "./NodeViewRenderer";
type ComponentViewConstructor = {
/** The editor instance. */
editor: Editor;
/** The extension the view belongs to. */
extension: Extension;
/** The node that the view is responsible for. */
node: ProsemirrorNode;
/** The editor view instance. */
view: EditorView;
/** A function that returns the current position of the node, or undefined once the view is destroyed. */
getPos: () => number | undefined;
/** The decorations applied to the node. */
decorations: Decoration[];
};
export default class ComponentView {
/** The class name applied to the editable content element of every node view. */
static readonly contentClassName = "component-content";
/** The React component to render. */
component: FunctionComponent<ComponentProps>;
/** The editor instance. */
editor: Editor;
/** The extension the view belongs to. */
extension: Extension;
/** The node that the view is responsible for. */
node: ProsemirrorNode;
/** The editor view instance. */
view: EditorView;
/** A function that returns the current position of the node, or undefined once the view is destroyed. */
getPos: () => number | undefined;
/** The decorations applied to the node. */
decorations: Decoration[];
/** The renderer instance. */
renderer: NodeViewRenderer<ComponentProps>;
/** Whether the node is selected. */
isSelected = false;
/** The DOM element that the node is rendered into. */
dom: HTMLElement | null;
/** The DOM element that the node's editable content is rendered into, if the node has editable content. */
contentDOM: HTMLElement | null = null;
/** The base class name for the node's DOM element. */
className?: string;
// See https://prosemirror.net/docs/ref/#view.NodeView
constructor(
component: FunctionComponent<ComponentProps>,
{
editor,
extension,
node,
view,
getPos,
decorations,
}: ComponentViewConstructor
) {
this.component = component;
this.editor = editor;
this.extension = extension;
this.getPos = getPos;
this.decorations = decorations;
this.node = node;
this.view = view;
this.dom = node.type.spec.inline
? document.createElement("span")
: document.createElement("div");
// Atoms have no directly editable content, and ProseMirror only marks a node
// view uneditable when it has no contentDOM.
if (!node.type.isAtom) {
this.contentDOM = document.createElement(
node.type.spec.inline ? "span" : "div"
);
// Chrome unwraps an attribute-less div that is the only child of its
// parent when a deletion empties a block inside it, which orphans the
// content from ProseMirror. Any attribute prevents this.
this.contentDOM.className = ComponentView.contentClassName;
}
this.className = `component-${node.type.name}`;
this.dom.classList.add(this.className);
this.renderer = new NodeViewRenderer(this.dom, this.component, this.props);
// Add the renderer to the editor's set of node renderers so that it is included in the React tree.
this.editor.nodeRenderers.add(this.renderer);
// Apply decoration classes to the DOM element.
this.applyDecorationClasses();
}
update(node: ProsemirrorNode, decorations: Decoration[]) {
if (node.type !== this.node.type) {
return false;
}
// Ensure we don't reuse NodeViews for different nodes that have a distinct identity
// This prevents attribute swapping during drag operations.
if (
this.node.attrs.id !== undefined &&
node.attrs.id !== this.node.attrs.id
) {
return false;
}
this.node = node;
this.decorations = decorations;
this.applyDecorationClasses();
this.renderer.updateProps(this.props);
return true;
}
/**
* Apply decoration classes to the DOM element.
* Extracts classes from inline decorations that overlap with this node's position.
*/
private applyDecorationClasses() {
if (!this.dom) {
return;
}
// Remove all existing decoration classes.
this.dom.classList.forEach((className) => {
if (className !== this.className) {
this.dom?.classList.remove(className);
}
});
// Apply classes from inline decorations.
this.decorations.forEach((decoration) => {
// For inline decorations, attrs contain the class property.
const attrs = (
decoration as Decoration & { type?: { attrs?: { class?: string } } }
).type?.attrs;
if (attrs?.class) {
const classes = attrs.class.split(" ");
classes.forEach((className) => {
if (className && this.dom) {
this.dom.classList.add(className);
}
});
}
});
}
selectNode() {
if (this.view.editable) {
this.isSelected = true;
this.renderer.updateProps(this.props);
}
}
deselectNode() {
if (this.view.editable) {
this.isSelected = false;
this.renderer.updateProps(this.props);
}
}
/**
* Ref callback for the component to mark the element that the node's
* editable content should be mounted within. The content itself is managed
* by ProseMirror rather than React.
*/
handleContentRef = (element: HTMLElement | null) => {
if (
!element ||
!this.contentDOM ||
element === this.contentDOM.parentElement
) {
return;
}
element.appendChild(this.contentDOM);
this.syncSelection();
};
stopEvent(event: Event) {
if (
this.contentDOM &&
event.target instanceof globalThis.Node &&
this.contentDOM.contains(event.target)
) {
return false;
}
return (
event.type !== "mousedown" &&
!event.type.startsWith("drag") &&
!event.type.startsWith("drop")
);
}
destroy() {
this.editor.nodeRenderers.delete(this.renderer);
this.dom = null;
this.contentDOM = null;
}
ignoreMutation(mutation: MutationRecord) {
if (this.contentDOM) {
return !this.contentDOM.contains(mutation.target);
}
return true;
}
get props() {
return {
node: this.node,
view: this.view,
isSelected: this.isSelected,
isEditable: this.view.editable,
getPos: this.getPos,
decorations: this.decorations,
contentRef: this.handleContentRef,
} as ComponentProps;
}
/**
* Re-apply the editor selection to the DOM once the content is mounted. React
* mounts the content after ProseMirror has already synced the selection, so a
* selection inside a freshly created node lands on a detached element and the
* browser leaves the caret after the node instead.
*/
private syncSelection() {
const { view } = this;
if (!this.dom || !view.hasFocus()) {
return;
}
const pos = this.getPos();
if (pos === undefined) {
return;
}
const { from, to } = view.state.selection;
if (from <= pos || to >= pos + this.node.nodeSize) {
return;
}
view.focus();
}
}