Open History to see the last commit
1import type { AssistantCitation } from "@t3tools/contracts";
2import {
3 $createLineBreakNode,
4 $createTextNode,
5 $getRoot,
6 $getSelection,
7 $isRangeSelection,
8 COMMAND_PRIORITY_HIGH,
9 PASTE_COMMAND,
10 type LexicalEditor,
11 type LexicalNode,
12} from "lexical";
13
14import { collectComposerPromptInlineTokens } from "../composer-editor-mentions";
15
16interface ComposerInlineTokenPasteOptions {
17 createMentionNode: (path: string) => LexicalNode;
18 createCitationNode: (citation: AssistantCitation, source: string) => LexicalNode;
19 getExpandedAbsoluteOffsetForPoint: (node: LexicalNode, pointOffset: number) => number;
20}
21
22export function registerComposerInlineTokenPaste(
23 editor: LexicalEditor,
24 options: ComposerInlineTokenPasteOptions,
25): () => void {
26 return editor.registerCommand(
27 PASTE_COMMAND,
28 (event) => {
29 if (!(event instanceof ClipboardEvent) || event.clipboardData === null) {
30 return false;
31 }
32 if (event.clipboardData.files.length > 0) {
33 return false;
34 }
35 const text = event.clipboardData.getData("text/plain");
36 if (text.length === 0) {
37 return false;
38 }
39 // Token grammar requires trailing whitespace; a virtual newline lets a
40 // mention at the very end of the pasted text still parse.
41 const tokens = collectComposerPromptInlineTokens(`${text}\n`).filter(
42 (token) =>
43 (token.type === "mention" || token.type === "citation") && token.end <= text.length,
44 );
45 if (tokens.length === 0) {
46 return false;
47 }
48
49 // Lexical command listeners already run inside an editor update. Starting
50 // a nested update here queues the token insertion until after this
51 // listener returns, which lets the plain-text paste handler run as well.
52 const selection = $getSelection();
53 if (!$isRangeSelection(selection)) {
54 return false;
55 }
56 const nodes: LexicalNode[] = [];
57 const appendText = (value: string) => {
58 const lines = value.split("\n");
59 for (let index = 0; index < lines.length; index += 1) {
60 const line = lines[index] ?? "";
61 if (line.length > 0) {
62 nodes.push($createTextNode(line));
63 }
64 if (index < lines.length - 1) {
65 nodes.push($createLineBreakNode());
66 }
67 }
68 };
69 const firstToken = tokens[0];
70 if (firstToken?.type === "mention" && firstToken.start === 0) {
71 const startPoint = selection.isBackward() ? selection.focus : selection.anchor;
72 const insertionOffset = options.getExpandedAbsoluteOffsetForPoint(
73 startPoint.getNode(),
74 startPoint.offset,
75 );
76 const precedingChar = $getRoot()
77 .getTextContent()
78 .slice(insertionOffset - 1, insertionOffset);
79 if (precedingChar.length > 0 && !/\s/.test(precedingChar)) {
80 nodes.push($createTextNode(" "));
81 }
82 }
83 let cursor = 0;
84 for (const token of tokens) {
85 if (token.start < cursor) {
86 continue;
87 }
88 if (token.start > cursor) {
89 appendText(text.slice(cursor, token.start));
90 }
91 nodes.push(
92 token.type === "citation"
93 ? options.createCitationNode(token.citation, token.source)
94 : options.createMentionNode(token.value),
95 );
96 cursor = token.end;
97 }
98 if (cursor < text.length) {
99 appendText(text.slice(cursor));
100 } else if (tokens.at(-1)?.type === "mention") {
101 // Keep the serialized prompt valid: mention tokens need trailing
102 // whitespace, so a paste ending in a mention gets the same
103 // trailing space the autocomplete inserts.
104 nodes.push($createTextNode(" "));
105 }
106 selection.insertNodes(nodes);
107 event.preventDefault();
108 return true;
109 },
110 COMMAND_PRIORITY_HIGH,
111 );
112}