Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(editor): keep the comment-box caret in the ordered list after switching issues (MUL-3973) (#4813)
n374c2903365a9c4
diff --git a/packages/views/editor/content-editor.test.tsx b/packages/views/editor/content-editor.test.tsxindex ae38388ee5..129102e66b 100644--- a/packages/views/editor/content-editor.test.tsx+++ b/packages/views/editor/content-editor.test.tsx@@ -42,6 +42,13 @@ vi.mock("./utils/preprocess", () => ({preprocessMarkdown: (value: string) => value,}));+// The real caret-restore logic needs a live ProseMirror doc (covered by+// restore-selection.test.ts). Here we only care that the sync effect reaches+// the dispatch, so return a sentinel selection.+vi.mock("./utils/restore-selection", () => ({+ clampSelectionToText: vi.fn(() => ({ __selection: true })),+}));+vi.mock("./bubble-menu", () => ({EditorBubbleMenu: () => null,}));@@ -61,6 +68,10 @@ vi.mock("./attachment-download-context", () => ({const editorRef = vi.hoisted<{ current: unknown }>(() => ({ current: null }));const onCreateFired = vi.hoisted(() => ({ value: false }));+// When true, the mock withholds `onCreate` — modelling Tiptap v3's real timing,+// where `onCreate` is deferred a tick after `useEditor` first hands back a+// non-null editor, so the content-sync effect runs before it.+const suppressOnCreate = vi.hoisted(() => ({ value: false }));const latestEditorOptions = vi.hoisted<{current?: { onUpdate?: (args: { editor: unknown }) => void };}>(() => ({}));@@ -86,6 +97,7 @@ vi.mock("@tiptap/react", () => ({setTextSelection: mockSetTextSelection,},getMarkdown: () => editorState.markdown,+ view: { dispatch: vi.fn() },state: {doc: {content: { size: 0 },@@ -96,10 +108,18 @@ vi.mock("@tiptap/react", () => ({},},selection: { empty: true, from: 0, to: 0 },+ // Minimal chainable transaction stub: the content-sync effect calls+ // `editor.state.tr.setSelection(...)` then hands the result to+ // `view.dispatch`. Real selection math lives in restore-selection.ts.+ tr: {+ setSelection() {+ return this;+ },+ },},};}- if (!onCreateFired.value) {+ if (!onCreateFired.value && !suppressOnCreate.value) {onCreateFired.value = true;options?.onCreate?.({ editor: editorRef.current });}@@ -113,6 +133,7 @@ vi.mock("@tiptap/react", () => ({}));import { ContentEditor, type ContentEditorRef } from "./content-editor";+import { clampSelectionToText } from "./utils/restore-selection";describe("ContentEditor", () => {beforeEach(() => {@@ -123,6 +144,7 @@ describe("ContentEditor", () => {editorState.uploadingNodes = [];editorRef.current = null;onCreateFired.value = false;+ suppressOnCreate.value = false;latestEditorOptions.current = undefined;providerProps.attachments = undefined;});@@ -242,6 +264,67 @@ describe("ContentEditor", () => {expect(mockSetContent).not.toHaveBeenCalled();});+ it("does not re-parse or move the caret on remount when the draft's markdown round-trip isn't byte-identical (ordered-list cursor bug)", () => {+ // RAS-27: the comment box remounts on issue switch and feeds the persisted+ // draft back as defaultValue. The editor mounts from that draft, but+ // @tiptap/markdown reserializes an ordered list slightly differently from+ // its source (here, an extra space). The normalized-markdown guard alone+ // treats that as an external change and re-parses — clamping the caret onto+ // the list's structural gap (caret "jumps to the second line"). The+ // parser-input guard must short-circuit instead: no setContent, no caret move.+ editorState.markdown = "1. buy milk"; // reserialized: differs from source+ render(<ContentEditor defaultValue="1. buy milk" />);++ expect(mockSetContent).not.toHaveBeenCalled();+ expect(clampSelectionToText).not.toHaveBeenCalled();+ });++ it("seeds the input guard synchronously so a remount short-circuits even before the deferred onCreate fires", () => {+ // Tiptap v3's onCreate runs a tick after the sync effect first sees a+ // non-null editor. If the guard were seeded only in onCreate it would be+ // null on that first run and the ordered-list draft would be re-parsed+ // anyway. Withhold onCreate and prove the render-time seed still short-circuits.+ suppressOnCreate.value = true;+ editorState.markdown = "1. buy milk"; // reserialized: differs from source+ render(<ContentEditor defaultValue="1. buy milk" />);++ expect(mockSetContent).not.toHaveBeenCalled();+ expect(clampSelectionToText).not.toHaveBeenCalled();+ });++ it("still applies a legitimate external revert after a local edit advanced the draft (A→B→A, no swallow)", () => {+ // Regression for the parser-input guard swallowing a valid external update:+ // description A, user edits to B (saved), defaultValue syncs to B, then a+ // collaborator reverts to A. The editor holds B, so A must be re-applied —+ // the guard must not treat A as "already applied" just because it once was.+ vi.useFakeTimers();+ const onUpdate = vi.fn();+ editorState.markdown = "A";+ const { rerender } = render(+ <ContentEditor defaultValue="A" onUpdate={onUpdate} debounceMs={100} />,+ );+ expect(mockSetContent).not.toHaveBeenCalled();++ // User edits to B; the debounced onUpdate advances lastEmitted to B.+ editorState.markdown = "B";+ act(() => {+ latestEditorOptions.current?.onUpdate?.({ editor: editorRef.current });+ vi.advanceTimersByTime(100);+ });++ // Server confirms: defaultValue -> B. Editor already holds B, so the effect+ // short-circuits (Guard 3) — and must advance the guard to B.+ rerender(<ContentEditor defaultValue="B" onUpdate={onUpdate} debounceMs={100} />);+ expect(mockSetContent).not.toHaveBeenCalled();++ // Collaborator reverts to A while the editor still holds B: must re-apply.+ rerender(<ContentEditor defaultValue="A" onUpdate={onUpdate} debounceMs={100} />);+ expect(mockSetContent).toHaveBeenCalledWith(+ "A",+ expect.objectContaining({ emitUpdate: false, contentType: "markdown" }),+ );+ });+it("does not sync when defaultValue normalizes to the current editor markdown", () => {editorState.markdown = "same content";const { rerender } = render(<ContentEditor defaultValue="same content" />);diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsxindex 51e7249728..45ec1beaef 100644--- a/packages/views/editor/content-editor.tsx+++ b/packages/views/editor/content-editor.tsx@@ -54,6 +54,7 @@ import type { MentionItem } from "./extensions/mention-suggestion";import { createEditorExtensions } from "./extensions";import { uploadAndInsertFile } from "./extensions/file-upload";import { preprocessMarkdown } from "./utils/preprocess";+import { clampSelectionToText } from "./utils/restore-selection";import { openLink, isMentionHref } from "./utils/link-handler";import { EditorBubbleMenu } from "./bubble-menu";import { useLinkHover, LinkHoverCard } from "./link-hover-card";@@ -219,6 +220,19 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(>(undefined);const mentionContextItemsRef = useRef<MentionItem[]>(mentionContextItems ?? []);const lastEmittedRef = useRef<string | null>(null);+ // The exact preprocessed markdown the editor's current document was built+ // from — seeded synchronously at first render (below) and kept in step with+ // the document thereafter: advanced whenever the sync effect re-parses AND+ // whenever it confirms the editor already matches `incoming` (Guard 3), so+ // it never lags behind what the editor actually holds. Re-applying the+ // identical input only rebuilds the same document and disturbs the caret;+ // comparing on the parser INPUT (not the serialized output) makes the+ // short-circuit robust to markdown whose round-trip isn't byte-identical,+ // e.g. an ordered list (`1. `). This is what stopped the "type `1.`, switch+ // issues, come back, caret jumps off the list item" bug: the comment box+ // remounts, the effect saw the redrawn draft as "changed", re-parsed it,+ // and the caret got clamped onto the list's structural gap.+ const appliedIncomingRef = useRef<string | null>(null);// In-session record of attachments freshly uploaded through this editor.// Surfaces (like the quick-create modal) that don't have a server-supplied@@ -298,6 +312,17 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(const queryClient = useQueryClient();const initialContent = defaultValue ? preprocessMarkdown(defaultValue) : "";+ // Seed the parser-input guard SYNCHRONOUSLY at first render. Tiptap v3's+ // `onCreate` is deferred (fires a tick after `useEditor` first hands the+ // component a non-null editor), so the content-sync effect can run before+ // it — seeding there would leave the ref null on that first run and let a+ // remount re-parse the draft anyway. `initialContent` is the exact input+ // the editor mounts from, so recording it here keeps the mount and its+ // first sync run consistent. Only the very first render seeds; later+ // divergence is tracked by the effect itself.+ if (appliedIncomingRef.current === null) {+ appliedIncomingRef.current = initialContent;+ }// Large markdown is parsed in chunks to dodge marked's O(n²) tokenizer (see// parseMarkdownChunked). Small docs stay on the single-parse fast path.const mountChunked = initialContent.length > MARKDOWN_CHUNK_THRESHOLD;@@ -441,10 +466,24 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(if (isDirty) return;const incoming = defaultValue ? preprocessMarkdown(defaultValue) : "";+ // Guard 2.5: the editor already holds the parse of this exact input+ // (from mount, or a previous run of this effect). Re-parsing produces an+ // identical document and only serves to move the caret — skip it. Unlike+ // Guard 3 below this compares the parser INPUT, so an ordered-list draft+ // whose serialization isn't byte-identical to its source (which slips+ // past the normalized-markdown check) still short-circuits here.+ if (incoming === appliedIncomingRef.current) return;const incomingNormalized = normalizeMarkdown(incoming);// Guard 3: normalized-equal short-circuit. Avoids a no-op transaction- // when the cache reflects a write this same editor just emitted.- if (incomingNormalized === current) return;+ // when the cache reflects a write this same editor just emitted. Record+ // this input as the one the current document reflects, so a later+ // external change back to an OLDER value (e.g. a collaborator reverts the+ // description) isn't mistaken by Guard 2.5 for an already-applied input+ // and swallowed.+ if (incomingNormalized === current) {+ appliedIncomingRef.current = incoming;+ return;+ }// Guard 4: `emitUpdate: false`. Tiptap v3's setContent defaults to// `emitUpdate: true`; without this we would re-trigger onUpdate →@@ -467,14 +506,18 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(});}- // Clamp prior selection to the new doc size so the caret doesn't snap- // to position 0 after ProseMirror replaces the document.- const docSize = editor.state.doc.content.size;- editor.commands.setTextSelection({- from: Math.min(from, docSize),- to: Math.min(to, docSize),- });-+ // Restore the caret after ProseMirror replaced the document. Snap the+ // prior offsets to the nearest VALID text positions instead of a bare+ // `Math.min` clamp — a clamped offset can resolve onto a structural+ // (non-text) boundary such as the gap before a list's first item, where+ // the caret visibly jumps to the next line. See clampSelectionToText.+ editor.view.dispatch(+ editor.state.tr.setSelection(+ clampSelectionToText(editor.state.doc, from, to),+ ),+ );++ appliedIncomingRef.current = incoming;lastEmittedRef.current = normalizeEditorMarkdown(editor);}, [defaultValue, editor]);diff --git a/packages/views/editor/utils/restore-selection.test.ts b/packages/views/editor/utils/restore-selection.test.tsnew file mode 100644index 0000000000..d4c7e5669f--- /dev/null+++ b/packages/views/editor/utils/restore-selection.test.ts@@ -0,0 +1,84 @@+import { afterEach, describe, expect, it } from "vitest";+import { Editor } from "@tiptap/core";+import StarterKit from "@tiptap/starter-kit";+import { TextSelection } from "@tiptap/pm/state";+import { clampSelectionToText } from "./restore-selection";++interface JsonNode {+ type: string;+ text?: string;+ content?: JsonNode[];+}++let editor: Editor | undefined;++function makeEditor(content: JsonNode): Editor {+ const element = document.createElement("div");+ document.body.appendChild(element);+ editor = new Editor({ element, extensions: [StarterKit], content });+ return editor;+}++afterEach(() => {+ editor?.destroy();+ editor = undefined;+ document.body.innerHTML = "";+});++/** doc > orderedList > listItem > paragraph("todo") */+const orderedListDoc: JsonNode = {+ type: "doc",+ content: [+ {+ type: "orderedList",+ content: [+ {+ type: "listItem",+ content: [{ type: "paragraph", content: [{ type: "text", text: "todo" }] }],+ },+ ],+ },+ ],+};++describe("clampSelectionToText", () => {+ it("snaps a structural offset onto real list text instead of the pre-item gap (ordered-list cursor bug)", () => {+ const ed = makeEditor(orderedListDoc);++ // Offset 1 is the gap between <orderedList> and its first <listItem> — a+ // non-text boundary. The old `setTextSelection({ from: Math.min(1, size) })`+ // parked the caret here, which the browser rendered on the next line.+ const sel = clampSelectionToText(ed.state.doc, 1, 1);++ expect(sel instanceof TextSelection).toBe(true);+ expect(sel.empty).toBe(true);+ // Snapped inside the list item's paragraph — a placeable text cursor.+ expect(sel.$from.parent.type.name).toBe("paragraph");+ expect(sel.$from.parent.isTextblock).toBe(true);+ // "todo" text spans positions 3..7; the snap lands at its start (3).+ expect(sel.from).toBe(3);+ });++ it("preserves an already-valid caret position unchanged", () => {+ const ed = makeEditor({+ type: "doc",+ content: [{ type: "paragraph", content: [{ type: "text", text: "hello" }] }],+ });++ // Position 3 sits between "he" and "llo" — a real text position.+ const sel = clampSelectionToText(ed.state.doc, 3, 3);++ expect(sel.from).toBe(3);+ expect(sel.$from.parent.isTextblock).toBe(true);+ });++ it("clamps an out-of-range offset to a valid text position at the document end", () => {+ const ed = makeEditor(orderedListDoc);++ const sel = clampSelectionToText(ed.state.doc, 999, 999);++ expect(sel.$from.parent.isTextblock).toBe(true);+ // End of the only text ("todo").+ expect(sel.from).toBe(7);+ });+});diff --git a/packages/views/editor/utils/restore-selection.ts b/packages/views/editor/utils/restore-selection.tsnew file mode 100644index 0000000000..c996219fa1--- /dev/null+++ b/packages/views/editor/utils/restore-selection.ts@@ -0,0 +1,28 @@+import { TextSelection, type Selection } from "@tiptap/pm/state";+import type { Node as ProseMirrorNode } from "@tiptap/pm/model";++/**+ * Map a pre-replace caret range onto the nearest VALID text positions of a+ * freshly rebuilt document.+ *+ * The content-sync effect used to restore the caret with a bare+ * `setTextSelection({ from: Math.min(from, docSize), to: Math.min(to, docSize) })`.+ * A clamped offset can land on a *structural* (non-text) boundary — e.g. the gap+ * between an `orderedList` and its first `listItem` — where ProseMirror has no+ * cursor and the browser paints the caret on the following line. That was the+ * visible half of the "type `1.`, switch issues, come back, caret jumps to the+ * second line" bug.+ *+ * `TextSelection.between` resolves each end and searches outward for a real+ * text position, so the returned selection is always a placeable cursor inside+ * a textblock — never a structural gap.+ */+export function clampSelectionToText(+ doc: ProseMirrorNode,+ from: number,+ to: number,+): Selection {+ const size = doc.content.size;+ const clamp = (pos: number) => Math.min(Math.max(pos, 0), size);+ return TextSelection.between(doc.resolve(clamp(from)), doc.resolve(clamp(to)));+}