Files
PaperClipAI/ui/src/lib/trailing-markdown-spaces.ts
T
DottaandPaperclip 29903bed59 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>
2026-11-15 22:15:00 -06:00

40 lines
1.7 KiB
TypeScript

import { fromMarkdown } from "mdast-util-from-markdown";
interface PositionedNode {
type: string;
position?: { start: { offset?: number }; end: { offset?: number } };
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.
* Only touch a document-final prose suffix. Entities before internal newlines or
* closing emphasis markers stay encoded: literal spaces there can create a
* hard break or invalidate emphasis. Code, HTML, and escaped literal entities
* must keep their source. Run on the exact export, before other unescaping.
*/
export function restoreTrailingMarkdownSpaces(markdown: string): string {
const suffix = /(?:&#x20;[ \t\r\n]*)+$/.exec(markdown);
if (!suffix) return markdown;
let node: PositionedNode = fromMarkdown(markdown);
while (node.children?.length) node = node.children[node.children.length - 1];
const start = node.position?.start.offset;
const end = node.position?.end.offset;
if (node.type !== "text" || start === undefined || end === undefined || end <= suffix.index) {
return markdown;
}
const text = markdown.slice(start, end).replace(/\\[\s\S]|&#x20;/g, (value, offset: number) =>
value === "&#x20;" && start + offset >= suffix.index ? " " : value);
return markdown.slice(0, start) + text + markdown.slice(end);
}