Skip to content

Commit d4567ab

Browse files
authored
fix(react): preserve selection when custom styles mount (#3314)
1 parent e454359 commit d4567ab

3 files changed

Lines changed: 179 additions & 47 deletions

File tree

‎packages/react/src/schema/ReactStyleSpec.browser.test.tsx‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
} from "@blocknote/core";
66
import { flushSync } from "react-dom";
77
import { createRoot } from "react-dom/client";
8+
import { TextSelection } from "@tiptap/pm/state";
89
import { expect, it } from "vite-plus/test";
910
import { userEvent } from "vite-plus/test/browser";
1011

@@ -19,6 +20,119 @@ const schema = BlockNoteSchema.create({
1920
styleSpecs: { ...defaultStyleSpecs, highlight },
2021
});
2122

23+
it.each([
24+
"cursor",
25+
"forward selection",
26+
"backward selection",
27+
"mixed selection",
28+
] as const)(
29+
"preserves the native selection when a React style mounts (%s)",
30+
async (selectionMode) => {
31+
const editor = BlockNoteEditor.create({
32+
schema,
33+
initialContent: [
34+
{
35+
type: "paragraph",
36+
content:
37+
selectionMode === "mixed selection"
38+
? [
39+
{ type: "text", text: "al", styles: {} },
40+
{ type: "text", text: "p", styles: { bold: true } },
41+
{ type: "text", text: "ha", styles: {} },
42+
]
43+
: "alpha",
44+
},
45+
],
46+
});
47+
const host = document.createElement("div");
48+
document.body.append(host);
49+
const root = createRoot(host);
50+
try {
51+
flushSync(() => root.render(<BlockNoteViewRaw editor={editor} />));
52+
const view = editor.prosemirrorView;
53+
const [anchor, head] =
54+
selectionMode === "cursor"
55+
? [5, 5]
56+
: selectionMode !== "backward selection"
57+
? [4, 7]
58+
: [7, 4];
59+
view.dispatch(
60+
view.state.tr.setSelection(
61+
TextSelection.create(view.state.doc, anchor, head),
62+
),
63+
);
64+
view.focus();
65+
expect(document.getSelection()?.toString()).toBe(
66+
selectionMode === "cursor" ? "" : "lph",
67+
);
68+
editor.addStyles({ highlight: true });
69+
70+
// Mounting a mark must preserve both endpoints, including a backwards
71+
// selection, rather than merely retaining the selected text.
72+
await expect
73+
.poll(() => {
74+
const selection = document.getSelection();
75+
if (!selection?.anchorNode || !selection.focusNode) {
76+
return undefined;
77+
}
78+
return [
79+
view.posAtDOM(selection.anchorNode, selection.anchorOffset),
80+
view.posAtDOM(selection.focusNode, selection.focusOffset),
81+
];
82+
})
83+
.toEqual([anchor, head]);
84+
85+
// The first character creates a mark view for a collapsed selection.
86+
// React may commit it after ProseMirror has already placed the caret.
87+
await userEvent.keyboard("X");
88+
await userEvent.keyboard("Y");
89+
90+
expect(editor.prosemirrorState.doc.textContent).toBe(
91+
selectionMode === "cursor" ? "alXYpha" : "aXYa",
92+
);
93+
expect(editor.getActiveStyles()).toMatchObject({ highlight: true });
94+
} finally {
95+
root.unmount();
96+
editor._tiptapEditor.destroy();
97+
host.remove();
98+
}
99+
},
100+
);
101+
102+
it("does not refocus the editor after a React style mounts", async () => {
103+
const editor = BlockNoteEditor.create({
104+
schema,
105+
initialContent: [{ type: "paragraph", content: "alpha" }],
106+
});
107+
const host = document.createElement("div");
108+
const input = document.createElement("input");
109+
document.body.append(host, input);
110+
const root = createRoot(host);
111+
try {
112+
flushSync(() => root.render(<BlockNoteViewRaw editor={editor} />));
113+
editor.prosemirrorView.focus();
114+
flushSync(() => {
115+
editor.updateBlock(editor.document[0], {
116+
content: [
117+
{ type: "text", text: "styled", styles: { highlight: true } },
118+
],
119+
});
120+
});
121+
// Focus can change between React's ref callback and reconciliation.
122+
input.focus();
123+
await userEvent.keyboard("X");
124+
125+
expect(document.activeElement).toBe(input);
126+
expect(input.value).toBe("X");
127+
expect(editor.prosemirrorState.doc.textContent).toBe("styled");
128+
} finally {
129+
root.unmount();
130+
editor._tiptapEditor.destroy();
131+
host.remove();
132+
input.remove();
133+
}
134+
});
135+
22136
it.each(["initial mount", "remount", "API remount"])(
23137
"keeps typing after text inserted with a React style (%s)",
24138
async (mountMode) => {

‎packages/react/src/schema/ReactStyleSpec.tsx‎

Lines changed: 37 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import {
1313
ReactMarkViewContext,
1414
ReactMarkViewRenderer,
1515
} from "@tiptap/react";
16-
import { FC, useContext } from "react";
16+
import { FC, useCallback, useContext } from "react";
1717
import { renderToDOMSpec } from "./@util/ReactRenderUtil.js";
1818

1919
// this file is mostly analogoues to `customBlocks.ts`, but for React blocks
@@ -88,44 +88,46 @@ export function createReactStyleSpec<T extends StyleConfig>(
8888
addMarkView() {
8989
const editor: BlockNoteEditor<any, any, any> = this.options.editor;
9090

91-
return (markViewProps) => {
92-
const renderResult = ReactMarkViewRenderer((props) => {
93-
const ref = useContext(ReactMarkViewContext).markViewContentRef;
91+
return ReactMarkViewRenderer((props) => {
92+
const ref = useContext(ReactMarkViewContext).markViewContentRef;
9493

95-
if (!ref) {
96-
throw new Error("markViewContentRef is not set");
97-
}
94+
if (!ref) {
95+
throw new Error("markViewContentRef is not set");
96+
}
9897

99-
const Content = styleImplementation.render;
100-
return (
101-
<Content
102-
editor={editor}
103-
contentRef={(element) => {
104-
ref(element);
105-
if (element) {
106-
element.dataset.markViewContent = "";
98+
const view = props.view;
99+
const contentRef = useCallback(
100+
(element: HTMLElement | null) => {
101+
ref(element);
102+
if (element) {
103+
element.dataset.markViewContent = "";
104+
// React can attach this content after ProseMirror maps selection.
105+
// EditorView.focus() resyncs it from the current editor state.
106+
// Wait until the commit/transaction finishes, and only reconcile
107+
// an already-focused editor.
108+
queueMicrotask(() => {
109+
if (!view.isDestroyed && view.hasFocus()) {
110+
view.focus();
107111
}
108-
}}
109-
value={
110-
styleConfig.propSchema === "boolean"
111-
? undefined
112-
: props.mark.attrs.stringValue
113-
}
114-
/>
115-
);
116-
})(markViewProps);
117-
118-
/**
119-
* See https://github.com/ueberdosis/tiptap/blob/5ba480bcd97a0e92f889019f1a65fc67fd3506f9/packages/react/src/ReactMarkViewRenderer.tsx#L98-L103
120-
* If the `contentRef` is not set synchronously, the contentDOM will be null
121-
* This is a hack to make sure that it is always defined so that Prosemirror can insert the content into the correct position
122-
*
123-
* (This is only an issue with Firefox)
124-
*/
125-
(renderResult as any).didMountContentDomElement = true;
112+
});
113+
}
114+
},
115+
[ref, view],
116+
);
126117

127-
return renderResult;
128-
};
118+
const Content = styleImplementation.render;
119+
return (
120+
<Content
121+
editor={editor}
122+
contentRef={contentRef}
123+
value={
124+
styleConfig.propSchema === "boolean"
125+
? undefined
126+
: props.mark.attrs.stringValue
127+
}
128+
/>
129+
);
130+
});
129131
},
130132
});
131133

‎tests/src/unit/react/staleNodeViewPos.test.tsx‎

Lines changed: 28 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { useLayoutEffect } from "react";
99
import { flushSync } from "react-dom";
1010
import { createRoot, type Root } from "react-dom/client";
1111
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
12+
import * as editorContent from "../../../../packages/react/src/editor/EditorContent.js";
1213

1314
/**
1415
* Regression tests for #2937 (and the same family: #2682, #2621).
@@ -111,6 +112,21 @@ function paragraphs(count: number, prefix: string) {
111112
}
112113

113114
function mountEditor(initialContent: any[]): ReproEditor {
115+
// Reproduce the synchronous node-view mounting used by older TipTap releases,
116+
// independently of whether ReactRenderer itself still calls flushSync.
117+
// Flush at BlockNote's portal registration boundary, while ProseMirror is
118+
// still reconciling, rather than after the command has already completed.
119+
const getContentComponent = editorContent.getContentComponent;
120+
vi.spyOn(editorContent, "getContentComponent").mockImplementation(() => {
121+
const contentComponent = getContentComponent();
122+
return {
123+
...contentComponent,
124+
setRenderer(...args) {
125+
flushSync(() => contentComponent.setRenderer(...args));
126+
},
127+
};
128+
});
129+
114130
div = document.createElement("div");
115131
document.body.appendChild(div);
116132

@@ -131,16 +147,10 @@ function mountEditor(initialContent: any[]): ReproEditor {
131147
root!.render(<BlockNoteViewRaw editor={editor as any} />);
132148
});
133149

134-
// TipTap's `ReactRenderer` only renders a node view synchronously (via
135-
// `flushSync`) when `isEditorContentInitialized` is set; otherwise it defers
136-
// to a microtask. TipTap's own `PureEditorContent` sets it, but BlockNote
137-
// replaces that component with its own mounting (`BlockNoteView.tsx`) and
138-
// never does, so BlockNote currently gets the deferred path by accident.
139-
// Set it here so node views mount the way they do for every other TipTap
140-
// React user — and the way they do for anyone resolving `@tiptap/react`
141-
// below 3.22, where this flag was still the always-true `isInitialized`.
142-
// That is the configuration #2937 was reported against.
143-
(editor as any)._tiptapEditor.isEditorContentInitialized = true;
150+
// Avoid ReactRenderer's initial microtask deferral (introduced in TipTap
151+
// 3.22). This flag no longer guarantees a synchronous React commit in newer
152+
// releases; the portal registration wrapper above supplies that separately.
153+
Object.assign(editor._tiptapEditor, { isEditorContentInitialized: true });
144154

145155
return editor;
146156
}
@@ -184,12 +194,18 @@ describe("stale node view getPos (#2937)", () => {
184194
{ type: "repro", content: "existing repro block" },
185195
...paragraphs(10, "tail"),
186196
]);
197+
let mounted = false;
198+
onMount = (_id, text) => {
199+
mounted ||= text === MARKER;
200+
};
187201
const errors = runCapturingErrors(() => {
188202
ed.replaceBlocks(ed.document.slice(0, 28), [
189203
{ type: "repro", content: MARKER } as any,
190204
]);
191205
});
192206

207+
// Even the non-reentrant control must actually mount during the command.
208+
expect(mounted).toBe(true);
193209
expect(errors).toEqual([]);
194210
// The straightforward case must not go anywhere near the fallback.
195211
expect(renderedFromFallbackCount).toBe(0);
@@ -207,8 +223,8 @@ describe("stale node view getPos (#2937)", () => {
207223
return;
208224
}
209225
fired = true;
210-
// Runs inside React's commit phase, which is inside the `flushSync` in
211-
// TipTap's `ReactRenderer` constructor, which is inside ProseMirror's
226+
// Runs inside React's commit phase, which is inside the test's
227+
// synchronous portal registration, which is inside ProseMirror's
212228
// `updateChildren`. Node views built or rendered from here see a
213229
// `getPos()` computed against a half-updated view-desc tree.
214230
ed.removeBlocks(ed.document.slice(-8));

0 commit comments

Comments
 (0)