mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-21 02:43:25 +01:00
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>
40 lines
1.7 KiB
TypeScript
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) + " ".repeat(suffix[0].length);
|
|
return restoreTrailingMarkdownSpaces(encoded) === markdown ? encoded : markdown;
|
|
}
|
|
|
|
/**
|
|
* The rich editor exports a final prose space as ` `. 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 = /(?: [ \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]| /g, (value, offset: number) =>
|
|
value === " " && start + offset >= suffix.index ? " " : value);
|
|
return markdown.slice(0, start) + text + markdown.slice(end);
|
|
}
|