fix(ui): add a space after composer autocomplete (#21754)

Preserve an ordinary space after composer autocomplete selections and place the caret after it. Cover all seven completion types and queries with trailing spaces.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-11-15 22:15:00 -06:00
1 parent f7a3497e9d
commit 29903bed59
6 files changed
+192 -28

No files matched your search

@@ -0,0 +1,135 @@
// @vitest-environment jsdom
import { act, useState } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { $getSelection, $isRangeSelection, getNearestEditorFromDOMNode } from "lexical";
import { buildSkillMentionHref } from "@paperclipai/shared";
import { MarkdownEditor, type MentionOption } from "./MarkdownEditor";
import type { SlashCommandOption } from "../context/EditorAutocompleteContext";
const mentions: MentionOption[] = [
{ id: "agent:ada", kind: "agent", agentId: "ada", name: "Ada" },
{ id: "user:pat", kind: "user", userId: "pat", name: "Pat" },
{ id: "project:paperclip", kind: "project", projectId: "paperclip", name: "Paperclip" },
{ id: "issue:task", kind: "issue", issueIdentifier: "TST-123", name: "TST-123 Example task" },
];
const commands: SlashCommandOption[] = [
{
id: "skill:deploy", kind: "skill", skillId: "deploy", key: "deploy", name: "Deploy",
slug: "deploy", description: null, href: buildSkillMentionHref("deploy", "deploy"), aliases: ["deploy"],
},
{
id: "routine:nightly", kind: "routine", routineId: "nightly", name: "Nightly",
status: "active", href: "routine://nightly", aliases: ["routine:Nightly"],
},
{ id: "action:goal", kind: "action", command: "goal", name: "Goal", description: "Set a goal", aliases: ["goal"] },
];
describe("MarkdownEditor autocomplete separators", () => {
let container: HTMLDivElement;
let root: ReturnType<typeof createRoot>;
let originalRangeRect: typeof Range.prototype.getBoundingClientRect;
beforeEach(() => {
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
vi.stubGlobal("ResizeObserver", class {
observe() {}
unobserve() {}
disconnect() {}
});
originalRangeRect = Range.prototype.getBoundingClientRect;
Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 10, 20);
container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
});
afterEach(async () => {
await act(async () => root.unmount());
container.remove();
Range.prototype.getBoundingClientRect = originalRangeRect;
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
it.each([
["skill", "/dep", "/deploy", true, ""],
["routine", "/routine:Nigh", "/routine:Nightly", true, ""],
["action", "/go", "/goal", false, ""],
["agent", "@Ada", "@Ada", true, ""],
["user", "@Pat", "@Pat", true, ""],
["project", "@Paper", "@Paperclip", true, ""],
["task", "@TST", "TST-123", true, ""],
["project after a typed space", "@Paperclip", "@Paperclip", true, " "],
["routine after typed spaces", "/routine:Nightly", "/routine:Nightly", true, " "],
])("keeps a space after a completed %s and types outside its link", async (_kind, value, completion, linked, typedSuffix) => {
const onChange = vi.fn();
function ControlledEditor() {
const [markdown, setMarkdown] = useState(value);
return <MarkdownEditor value={markdown} onChange={(next) => {
onChange(next);
setMarkdown(next);
}} actionCommands={commands} mentions={mentions} />;
}
await act(async () => {
root.render(<ControlledEditor />);
});
const editable = container.querySelector<HTMLElement>('[contenteditable="true"]')!;
expect(editable).not.toBeNull();
await act(async () => {
editable.focus();
const range = document.createRange();
range.selectNodeContents(editable.querySelector('[data-lexical-text="true"]')!.firstChild!);
range.collapse(false);
const selection = window.getSelection()!;
selection.removeAllRanges();
selection.addRange(range);
document.dispatchEvent(new Event("selectionchange"));
});
if (typedSuffix) {
const editor = getNearestEditorFromDOMNode(editable)!;
await act(async () => {
editor.update(() => {
const selection = $getSelection();
expect($isRangeSelection(selection)).toBe(true);
if ($isRangeSelection(selection)) selection.insertText(typedSuffix);
});
});
await act(async () => document.dispatchEvent(new Event("selectionchange")));
}
await vi.waitFor(() => expect(document.querySelector('[data-testid="mention-autocomplete-menu"]')).not.toBeNull());
await act(async () => {
editable.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true, cancelable: true }));
});
await vi.waitFor(() => {
expect(editable.textContent).toBe(`${completion} `);
expect(editable.querySelector("a")?.textContent ?? null).toBe(linked ? completion : null);
const caretPrefix = document.createRange();
caretPrefix.selectNodeContents(editable);
const selection = window.getSelection()!;
caretPrefix.setEnd(selection.anchorNode!, selection.anchorOffset);
expect(caretPrefix.toString()).toBe(`${completion} `);
});
expect(onChange.mock.lastCall?.[0]).toMatch(/ $/);
expect(onChange.mock.lastCall?.[0]).not.toContain("\u00a0");
expect(document.querySelector('[data-testid="mention-autocomplete-menu"]')).toBeNull();
const editor = getNearestEditorFromDOMNode(editable)!;
await act(async () => {
document.dispatchEvent(new Event("selectionchange"));
editor.update(() => {
const selection = $getSelection();
expect($isRangeSelection(selection)).toBe(true);
if ($isRangeSelection(selection)) selection.insertText("next");
});
});
expect(editable.textContent).toBe(`${completion} next`);
expect(editable.querySelector("a")?.textContent ?? null).toBe(linked ? completion : null);
expect(onChange.mock.lastCall?.[0]).toMatch(/ next$/);
expect(onChange.mock.lastCall?.[0]).not.toContain("\u00a0");
});
});
+4 -4
View File
@@ -193,7 +193,7 @@ vi.mock("@mdxeditor/editor", async () => {
}}
>
{/* The real editor paints resolved text, never the escapes that carried it in. */}
{content.replace(/\\</g, "<") || placeholder || ""}
{content.replace(/\\</g, "<").replace(/(?:&#x20;)+$/, (suffix) => " ".repeat(suffix.length / 6)) || placeholder || ""}
</div>
);
});
@@ -1710,14 +1710,14 @@ describe("MarkdownEditor", () => {
it("places the caret after a plain action command", () => {
const editable = document.createElement("div");
editable.contentEditable = "true";
editable.textContent = "/goal\u00a0";
editable.innerHTML = '<p><span data-lexical-text="true">/goal </span></p>';
document.body.appendChild(editable);
expect(placeCaretAtEditableEnd(editable)).toBe(true);
const selection = window.getSelection();
expect(selection?.anchorNode).toBe(editable);
expect(selection?.anchorOffset).toBe(1);
expect(selection?.anchorNode).toBe(editable.querySelector("span")?.firstChild);
expect(selection?.anchorOffset).toBe("/goal ".length);
editable.remove();
});
+26 -22
View File
@@ -60,7 +60,7 @@ import {
import { unescapeBlockquoteMarkers } from "../lib/blockquote-markdown";
import { unescapeIntrawordUnderscores } from "../lib/underscore-markdown";
import { unescapeEqualsSigns } from "../lib/equals-markdown";
import { restoreTrailingMarkdownSpaces } from "../lib/trailing-markdown-spaces";
import { preserveTrailingMarkdownSpaces, restoreTrailingMarkdownSpaces } from "../lib/trailing-markdown-spaces";
import { pasteNormalizationPlugin } from "../lib/paste-normalization";
import { cn } from "../lib/utils";
import { useEditorAutocomplete, type SlashCommandOption } from "../context/EditorAutocompleteContext";
@@ -181,7 +181,7 @@ function prepareMarkdownForEditor(value: string): string {
// HTML construct would throw and drop the whole component to raw source.
// Escaping those brackets keeps ordinary prose — `<name>`, `</close>` — in the
// rich editor. `toStoredMarkdown` reverses it on the way out.
return escapeUnsupportedAngleBrackets(withImages);
return preserveTrailingMarkdownSpaces(escapeUnsupportedAngleBrackets(withImages));
}
/**
@@ -591,16 +591,16 @@ function mentionMarkdown(option: MentionOption): string {
// Insert a compact issue link (e.g. `[PAP-123](/issues/PAP-123)`). The chip
// decorator recognizes this href as an `issue` mention and renders it as a
// task chip; MarkdownBody linkifies the same href on display.
return `[${option.issueIdentifier}](${buildIssueReferenceHref(option.issueIdentifier)}) `;
return `[${option.issueIdentifier}](${buildIssueReferenceHref(option.issueIdentifier)})`;
}
if (option.kind === "project" && option.projectId) {
return `[@${option.name}](${buildProjectMentionHref(option.projectId, option.projectColor ?? null)}) `;
return `[@${option.name}](${buildProjectMentionHref(option.projectId, option.projectColor ?? null)})`;
}
if (option.kind === "user" && option.userId) {
return `[@${option.name}](${buildUserMentionHref(option.userId)}) `;
return `[@${option.name}](${buildUserMentionHref(option.userId)})`;
}
const agentId = option.agentId ?? option.id.replace(/^agent:/, "");
return `[@${option.name}](${buildAgentMentionHref(agentId, option.agentIcon ?? null)}) `;
return `[@${option.name}](${buildAgentMentionHref(agentId, option.agentIcon ?? null)})`;
}
function slashCommandLabel(option: SlashCommandOption): string {
@@ -610,20 +610,18 @@ function slashCommandLabel(option: SlashCommandOption): string {
}
function slashCommandMarkdown(option: SlashCommandOption): string {
// MDXEditor trims an ordinary trailing space when setMarkdown re-imports the
// command. Keep a non-breaking separator in the document so subsequent text
// is inserted as the command argument instead of being glued to the token.
if (option.kind === "action") return `/${option.command}\u00a0`;
if (option.kind === "action") return `/${option.command}`;
if (option.kind === "routine") {
return `[${slashCommandLabel(option)}](${buildRoutineMentionHref(option.routineId)}) `;
return `[${slashCommandLabel(option)}](${buildRoutineMentionHref(option.routineId)})`;
}
return `[/${option.slug}](${option.href}) `;
return `[/${option.slug}](${option.href})`;
}
function autocompleteMarkdown(option: AutocompleteOption): string {
return option.kind === "skill" || option.kind === "routine" || option.kind === "action"
const token = option.kind === "skill" || option.kind === "routine" || option.kind === "action"
? slashCommandMarkdown(option)
: mentionMarkdown(option);
return `${token} `;
}
export function shouldAcceptAutocompleteKey(
@@ -707,17 +705,20 @@ export function placeCaretAfterMentionAnchor(target: HTMLAnchorElement): boolean
const range = document.createRange();
const nextSibling = target.nextSibling;
if (nextSibling?.nodeType === Node.TEXT_NODE) {
const text = nextSibling.textContent ?? "";
if (text.startsWith(" ")) {
range.setStart(nextSibling, 1);
const nextText = nextSibling instanceof HTMLElement && nextSibling.hasAttribute("data-lexical-text")
? nextSibling.firstChild
: nextSibling;
if (nextText?.nodeType === Node.TEXT_NODE) {
const text = nextText.textContent ?? "";
if (text.startsWith(" ") || text.startsWith("\u00a0")) {
range.setStart(nextText, 1);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
return true;
}
if (text.length > 0) {
range.setStart(nextSibling, 0);
range.setStart(nextText, 0);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
@@ -736,7 +737,9 @@ export function placeCaretAtEditableEnd(target: HTMLElement): boolean {
const selection = window.getSelection();
if (!selection) return false;
const range = document.createRange();
range.selectNodeContents(target);
let end: Node = target;
while (end.lastChild) end = end.lastChild;
range.selectNodeContents(end.nodeType === Node.TEXT_NODE ? end : target);
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
@@ -745,11 +748,12 @@ export function placeCaretAtEditableEnd(target: HTMLElement): boolean {
/** Replace the active autocomplete token in the markdown string with the selected token. */
function applyMention(markdown: string, state: MentionState, option: AutocompleteOption): string {
const source = restoreTrailingMarkdownSpaces(markdown);
const search = `${state.marker}${state.query}`;
const replacement = autocompleteMarkdown(option);
const idx = markdown.lastIndexOf(search);
const idx = source.lastIndexOf(search);
if (idx === -1) return markdown;
return markdown.slice(0, idx) + replacement + markdown.slice(idx + search.length);
return source.slice(0, idx) + replacement + source.slice(idx + search.length);
}
/* ---- Component ---- */
@@ -1232,7 +1236,7 @@ export const MarkdownEditor = forwardRef<MarkdownEditorRef, MarkdownEditorProps>
if (!state) return false;
if (option.kind === "action" && option.disabled) return false;
const current = latestValueRef.current;
const next = applyMention(current, state, option);
const next = preserveTrailingMarkdownSpaces(applyMention(current, state, option));
if (next !== current) {
latestValueRef.current = next;
echoIgnoreMarkdownRef.current = next;
@@ -88,7 +88,7 @@ vi.mock("@mdxeditor/editor", async () => {
() => ({
setMarkdown: (value: string) => {
contentRef.current = value;
if (editableRef.current) editableRef.current.textContent = value;
if (editableRef.current) editableRef.current.textContent = value.replace(/(?:&#x20;)+$/, (suffix) => " ".repeat(suffix.length / 6));
},
insertMarkdown: (value: string) => {
const next = contentRef.current
+19 -1
View File
@@ -1,5 +1,23 @@
import { describe, expect, it } from "vitest";
import { restoreTrailingMarkdownSpaces } from "./trailing-markdown-spaces";
import { preserveTrailingMarkdownSpaces, restoreTrailingMarkdownSpaces } from "./trailing-markdown-spaces";
describe("preserveTrailingMarkdownSpaces", () => {
it.each([
["[/deploy](skill://deploy) ", "[/deploy](skill://deploy)&#x20;"],
["/goal ", "/goal&#x20;"],
["Send this ", "Send this&#x20;&#x20;"],
["Use `code` ", "Use `code`&#x20;"],
])("preserves a final prose space through import: %s", (input, expected) => {
expect(preserveTrailingMarkdownSpaces(input)).toBe(expected);
expect(restoreTrailingMarkdownSpaces(expected)).toBe(input);
});
it.each(["", "No suffix", "Keep \nthis", "```text\ncode ", " code ", "<div>\ntext ", String.raw`literal\ `])(
"leaves other content unchanged: %s", (input) => {
expect(preserveTrailingMarkdownSpaces(input)).toBe(input);
},
);
});
describe("restoreTrailingMarkdownSpaces", () => {
it.each([
+7
View File
@@ -6,6 +6,13 @@ interface PositionedNode {
children?: PositionedNode[];
}
export function preserveTrailingMarkdownSpaces(markdown: string): string {
const suffix = / +$/.exec(markdown);
if (!suffix) return markdown;
const encoded = markdown.slice(0, suffix.index) + "&#x20;".repeat(suffix[0].length);
return restoreTrailingMarkdownSpaces(encoded) === markdown ? encoded : markdown;
}
/**
* The rich editor exports a final prose space as `&#x20;`. Restore that space
* before storing the draft so message submission can trim it normally.