Skip to content

Commit 0745612

Browse files
tellahoMongo
andauthored
fix(composer): preserve caret when inserting mentions mid-message (#6531)
**Category:** fix **User Impact:** Users can insert mentions earlier in a draft and continue typing without the caret corrupting the rest of the message. **Problem:** Caret correction ran after every document change, so typing a mention before existing text repeatedly advanced across the mention separator and interleaved spaces into the draft. **Solution:** Limit correction to the autocomplete settlement it was designed for, with transaction-level and browser-level regression coverage for known and unregistered mentions. <details> <summary>File changes</summary> **desktop/src/features/messages/lib/mentionHighlightExtension.ts** Restricts trailing-space caret advancement to an armed autocomplete settlement instead of every document change. **desktop/src/features/messages/lib/mentionHighlightExtension.test.mjs** Exercises the real ProseMirror plugin state and verifies mid-draft mention typing, unknown tokens, end-of-message typing, and completed-mention separators. **desktop/tests/e2e/mentions.spec.ts** Reproduces the reported composer workflow in Chromium and covers the same corruption path for an unregistered `@token`. </details> ## Reproduction steps 1. Open a channel and enter `hello world` in the composer. 2. Move the caret between `hello` and ` world`. 3. Type ` @bo`, select `bob` from autocomplete, and continue typing `abc`. 4. Confirm the composer reads `hello @bob abc world` with the caret after `abc`. 5. Repeat with an unregistered token such as ` @zzq` and confirm the existing text remains intact. ## Before / After | Before | After | | --- | --- | | Typing after a mid-draft mention walks the caret through the existing message. | Continued typing stays after the inserted mention. | | ![Before: mention caret corrupts existing draft text](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/6531/mention-caret-before.gif) | ![After: caret remains after the inserted mention](https://d24qwcpro867f5.cloudfront.net/repos/buzz/prs/6531/mention-caret-after.gif) | --------- Signed-off-by: Taylor Ho <[email protected]> Co-authored-by: Mongo <5398c5fd039b963ce132b3e078e7c4af097dd997517bb5e14c2682fe68c25197@buzz.block.builderlab.xyz>
1 parent f794216 commit 0745612

3 files changed

Lines changed: 130 additions & 15 deletions

File tree

‎desktop/src/features/messages/lib/mentionHighlightExtension.test.mjs‎

Lines changed: 76 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
22
import test from "node:test";
33

44
import { getSchema } from "@tiptap/core";
5+
import { EditorState, TextSelection } from "@tiptap/pm/state";
56
import StarterKit from "@tiptap/starter-kit";
67

78
import {
@@ -10,6 +11,7 @@ import {
1011
createMentionCaretSettlement,
1112
findHighlightMatches,
1213
insertPosForMentionTextInput,
14+
MentionHighlightExtension,
1315
mentionTextInputInsertPos,
1416
positionAfterArrowLeftThroughMentionSpace,
1517
selectionAfterMentionTrailingSpace,
@@ -213,7 +215,6 @@ test("shouldAdvanceMentionCaret restores a remap while this editor is settling",
213215
from: 7,
214216
next: 8,
215217
settling: true,
216-
docChanged: false,
217218
}),
218219
true,
219220
);
@@ -225,21 +226,18 @@ test("shouldAdvanceMentionCaret does not steal ArrowLeft after settlement is can
225226
from: 7,
226227
next: 8,
227228
settling: false,
228-
docChanged: false,
229229
}),
230230
false,
231231
);
232232
});
233233

234-
test("shouldAdvanceMentionCaret still advances after a document change", () => {
234+
test("shouldAdvanceMentionCaret does not advance on an unsettled document change", () => {
235+
// Regression: `docChanged` used to force an advance. That walked the caret
236+
// across a mention's trailing space on every keystroke, so typing `@name`
237+
// before existing text interleaved spaces into the draft.
235238
assert.equal(
236-
shouldAdvanceMentionCaret({
237-
from: 7,
238-
next: 8,
239-
settling: false,
240-
docChanged: true,
241-
}),
242-
true,
239+
shouldAdvanceMentionCaret({ from: 7, next: 8, settling: false }),
240+
false,
243241
);
244242
});
245243

@@ -312,3 +310,71 @@ test("assignMentionHighlightNames updates when a new mention is added", () => {
312310
);
313311
assert.deepEqual(storage.names, ["bob", "quinn"]);
314312
});
313+
314+
// ── caret regression: typing a mention before existing text ───────────
315+
//
316+
// Drives the real plugin through EditorState so `appendTransaction` runs.
317+
// Before the fix, every keystroke advanced the caret across a mention's
318+
// trailing space, interleaving spaces into the rest of the draft.
319+
320+
function editorStateWithMentionHighlight(initialText, names) {
321+
// The plugin factory only reads `this.storage`, so a minimal stand-in is
322+
// enough to exercise it without constructing a full editor (needs a DOM).
323+
const plugins = MentionHighlightExtension.config.addProseMirrorPlugins.call({
324+
storage: { names, agentNames: [], channelNames: [] },
325+
});
326+
return EditorState.create({
327+
doc: document(paragraph(text(initialText))),
328+
schema,
329+
plugins,
330+
});
331+
}
332+
333+
/** Insert `typed` one character at a time at `startPos`, as typing does. */
334+
function typeAt(state, startPos, typed) {
335+
let next = state.apply(
336+
state.tr.setSelection(TextSelection.create(state.doc, startPos)),
337+
);
338+
for (const char of typed) {
339+
const { from, to } = next.selection;
340+
const tr = next.tr.insertText(char, from, to);
341+
tr.setSelection(TextSelection.create(tr.doc, tr.mapping.map(to, 1)));
342+
next = next.apply(tr);
343+
}
344+
return next;
345+
}
346+
347+
test("typing a mention before existing text does not interleave spaces", () => {
348+
// Caret placed just after "hello" in "hello world", then " @qu" is typed.
349+
const state = editorStateWithMentionHighlight("hello world", ["quinn"]);
350+
const typed = typeAt(state, 1 + "hello".length, " @qu");
351+
assert.equal(typed.doc.textContent, "hello @qu world");
352+
});
353+
354+
test("typing a mention before existing text keeps the caret with the text", () => {
355+
const state = editorStateWithMentionHighlight("hello world", ["quinn"]);
356+
const typed = typeAt(state, 1 + "hello".length, " @qu");
357+
assert.equal(typed.selection.from, 1 + "hello @qu".length);
358+
});
359+
360+
test("an unknown @token before existing text is not rewritten either", () => {
361+
// The trailing-space scan is purely textual, so it fired even for names
362+
// that were never registered as mentions.
363+
const state = editorStateWithMentionHighlight("hello world", []);
364+
const typed = typeAt(state, 1 + "hello".length, " @zz");
365+
assert.equal(typed.doc.textContent, "hello @zz world");
366+
});
367+
368+
test("typing a mention at the end of a message still works", () => {
369+
const state = editorStateWithMentionHighlight("hello world", ["quinn"]);
370+
const typed = typeAt(state, 1 + "hello world".length, " @qu");
371+
assert.equal(typed.doc.textContent, "hello world @qu");
372+
});
373+
374+
test("typing after a completed mention keeps the separator intact", () => {
375+
// "@quinn " already exists; typing at the very end must not consume or
376+
// duplicate the trailing space.
377+
const state = editorStateWithMentionHighlight("@quinn world", ["quinn"]);
378+
const typed = typeAt(state, 1 + "@quinn world".length, "!");
379+
assert.equal(typed.doc.textContent, "@quinn world!");
380+
});

‎desktop/src/features/messages/lib/mentionHighlightExtension.ts‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,19 +40,22 @@ export function createMentionCaretSettlement(): MentionCaretSettlement {
4040
* Whether to move an empty caret from `from` to `next` after a mention
4141
* trailing space. Settlement is per editor: autocomplete arms it, and
4242
* ArrowLeft/click cancel it so we do not steal an intentional caret.
43+
*
44+
* Only an armed settlement may advance the caret. Advancing on any
45+
* document change instead walked the caret across the separator on every
46+
* keystroke, so typing `@name` before existing text interleaved spaces
47+
* into the draft (`hello @q uworld`).
4348
*/
4449
export function shouldAdvanceMentionCaret({
4550
from,
4651
next,
4752
settling,
48-
docChanged,
4953
}: {
5054
from: number;
5155
next: number;
5256
settling: boolean;
53-
docChanged: boolean;
5457
}): boolean {
55-
return next !== from && (settling || docChanged);
58+
return next !== from && settling;
5659
}
5760

5861
/**
@@ -334,7 +337,7 @@ export const MentionHighlightExtension = Extension.create({
334337
return oldDecorations.map(tr.mapping, tr.doc);
335338
},
336339
},
337-
appendTransaction(transactions, _oldState, newState) {
340+
appendTransaction(_transactions, _oldState, newState) {
338341
if (!newState.selection.empty) {
339342
settlement.cancel();
340343
return null;
@@ -346,7 +349,6 @@ export const MentionHighlightExtension = Extension.create({
346349
from,
347350
next,
348351
settling: settlement.peek() !== null,
349-
docChanged: transactions.some((tr) => tr.docChanged),
350352
})
351353
) {
352354
return null;

‎desktop/tests/e2e/mentions.spec.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -885,6 +885,53 @@ test("clicking a person mention chip edge is not treated as after the trailing s
885885
expect(text).not.toMatch(/@bob x/);
886886
});
887887

888+
test("typing a mention before existing text does not interleave spaces", async ({
889+
page,
890+
}) => {
891+
// Regression (the reported repro): with a draft already written, place the
892+
// caret earlier in the message, type a partial mention, pick a suggestion,
893+
// then keep typing. Caret correction used to fire on every document change
894+
// and walk the caret across the mention's trailing space, so each keystroke
895+
// pushed a space further into the rest of the draft.
896+
await page.goto("/");
897+
await page.getByTestId("channel-general").click();
898+
await expect(page.getByTestId("chat-title")).toHaveText("general");
899+
900+
const input = page.getByTestId("message-input");
901+
await input.fill("hello world");
902+
903+
// Click between "hello" and " world", then open autocomplete there.
904+
await input.focus();
905+
for (let i = 0; i < " world".length; i++) {
906+
await page.keyboard.press("ArrowLeft");
907+
}
908+
await page.keyboard.type(" @bo");
909+
await autocomplete(page).getByText("bob").click();
910+
await page.keyboard.type("abc");
911+
912+
await expect(input).toHaveText("hello @bob abc world");
913+
});
914+
915+
test("typing an unregistered @token before existing text is left alone", async ({
916+
page,
917+
}) => {
918+
// The trailing-space scan is purely textual, so it also fired for tokens
919+
// that were never registered as mentions.
920+
await page.goto("/");
921+
await page.getByTestId("channel-general").click();
922+
await expect(page.getByTestId("chat-title")).toHaveText("general");
923+
924+
const input = page.getByTestId("message-input");
925+
await input.fill("hello world");
926+
await input.focus();
927+
for (let i = 0; i < " world".length; i++) {
928+
await page.keyboard.press("ArrowLeft");
929+
}
930+
await page.keyboard.type(" @zzq");
931+
932+
await expect(input).toHaveText("hello @zzq world");
933+
});
934+
888935
test("channel references keep caret movement through the channel name", async ({
889936
page,
890937
}) => {

0 commit comments

Comments
 (0)