Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

composerInlineTokenPaste.ts

200 lines7.3 KB

1import { ComposerContextId } from "@t3tools/contracts";
2import type { AssistantCitation, ComposerContextClipboardFragment } from "@t3tools/contracts";
3import {
4 COMPOSER_CONTEXT_CLIPBOARD_MIME,
5 decodeComposerContextFragment,
6 decodeComposerContextClipboardHtml,
7} from "@t3tools/shared/composerContextClipboard";
8import {
9 collectComposerContextReferences,
10 formatComposerContextReference,
11 replaceComposerContextReferences,
12} from "@t3tools/shared/composerContextReferences";
13import {
14 $createLineBreakNode,
15 $createTextNode,
16 $getRoot,
17 $getSelection,
18 $isRangeSelection,
19 COMMAND_PRIORITY_HIGH,
20 PASTE_COMMAND,
21 type LexicalEditor,
22 type LexicalNode,
23} from "lexical";
24​
25import { collectComposerPromptInlineTokens } from "../composer-editor-mentions";
26​
27interface ComposerInlineTokenPasteOptions {
28 createMentionNode: (path: string) => LexicalNode;
29 createCitationNode: (citation: AssistantCitation, source: string) => LexicalNode;
30 createContextReferenceNode: (reference: {
31 kind: string;
32 contextId: string;
33 label: string;
34 }) => LexicalNode;
35 getExpandedAbsoluteOffsetForPoint: (node: LexicalNode, pointOffset: number) => number;
36 /**
37 * Imports the records behind a structured paste into the draft. Returns the ids that had
38 * to change (a re-attached binary gets a fresh local id) so the pasted links follow.
39 */
40 importContextFragment?: (
41 fragment: ComposerContextClipboardFragment,
42 ) => ReadonlyMap<string, string>;
44​
45export function registerComposerInlineTokenPaste(
46 editor: LexicalEditor,
47 options: ComposerInlineTokenPasteOptions,
48): () => void {
49 return editor.registerCommand(
50 PASTE_COMMAND,
51 (event) => {
52 if (!(event instanceof ClipboardEvent) || event.clipboardData === null) {
53 return false;
54 }
55 if (event.clipboardData.files.length > 0) {
56 return false;
57 }
58 const pastedText = event.clipboardData.getData("text/plain");
59 if (pastedText.length === 0) {
60 return false;
61 }
62 const text = importPastedComposerText(event.clipboardData, options.importContextFragment);
63 // Token grammar requires trailing whitespace; a virtual newline lets a
64 // mention at the very end of the pasted text still parse.
65 const tokens = collectComposerPromptInlineTokens(`${text}\n`).filter(
66 (token) =>
67 (token.type === "mention" ||
68 token.type === "citation" ||
69 token.type === "context-reference") &&
70 token.end <= text.length,
71 );
72 if (tokens.length === 0) {
73 return false;
74 }
75​
76 // Lexical command listeners already run inside an editor update. Starting
77 // a nested update here queues the token insertion until after this
78 // listener returns, which lets the plain-text paste handler run as well.
79 const selection = $getSelection();
80 if (!$isRangeSelection(selection)) {
81 return false;
82 }
83 const nodes: LexicalNode[] = [];
84 const appendText = (value: string) => {
85 const lines = value.split("\n");
86 for (let index = 0; index < lines.length; index += 1) {
87 const line = lines[index] ?? "";
88 if (line.length > 0) {
89 nodes.push($createTextNode(line));
90 }
91 if (index < lines.length - 1) {
92 nodes.push($createLineBreakNode());
93 }
94 }
95 };
96 const firstToken = tokens[0];
97 if (firstToken?.type === "mention" && firstToken.start === 0) {
98 const startPoint = selection.isBackward() ? selection.focus : selection.anchor;
99 const insertionOffset = options.getExpandedAbsoluteOffsetForPoint(
100 startPoint.getNode(),
101 startPoint.offset,
102 );
103 const precedingChar = $getRoot()
104 .getTextContent()
105 .slice(insertionOffset - 1, insertionOffset);
106 if (precedingChar.length > 0 && !/\s/.test(precedingChar)) {
107 nodes.push($createTextNode(" "));
108 }
109 }
110 let cursor = 0;
111 for (const token of tokens) {
112 if (token.start < cursor) {
113 continue;
114 }
115 if (token.start > cursor) {
116 appendText(text.slice(cursor, token.start));
117 }
118 nodes.push(
119 token.type === "citation"
120 ? options.createCitationNode(token.citation, token.source)
121 : token.type === "context-reference"
122 ? options.createContextReferenceNode({
123 kind: token.kind,
124 contextId: token.contextId,
125 label: token.label,
126 })
127 : options.createMentionNode(token.value),
128 );
129 cursor = token.end;
130 }
131 if (cursor < text.length) {
132 appendText(text.slice(cursor));
133 } else if (tokens.at(-1)?.type === "mention") {
134 // Keep the serialized prompt valid: mention tokens need trailing
135 // whitespace, so a paste ending in a mention gets the same
136 // trailing space the autocomplete inserts.
137 nodes.push($createTextNode(" "));
138 }
139 selection.insertNodes(nodes);
140 event.preventDefault();
141 return true;
142 },
143 COMMAND_PRIORITY_HIGH,
144 );
146​
147/** Clipboard records referenced by the copied text, including dependent screenshots. */
148export function readPastedComposerContext(
149 clipboardData: Pick<DataTransfer, "getData">,
150): ComposerContextClipboardFragment | null {
151 const pastedText = clipboardData.getData("text/plain");
152 // Only records whose links are in the pasted text get imported; a fragment may carry
153 // more (it was built for a larger copy) and must not start transfers for those.
154 const decodedFragment =
155 decodeComposerContextFragment(clipboardData.getData(COMPOSER_CONTEXT_CLIPBOARD_MIME)) ??
156 decodeComposerContextClipboardHtml(clipboardData.getData("text/html"));
157 if (decodedFragment === null) return null;
158 const pastedIds = new Set<string>(
159 collectComposerContextReferences(pastedText).map((occurrence) => occurrence.contextId),
160 );
161 for (const record of decodedFragment.records) {
162 if (
163 record.kind === "preview-annotation" &&
164 !("payload" in record) &&
165 pastedIds.has(record.contextId) &&
166 record.screenshotContextId
167 ) {
168 pastedIds.add(record.screenshotContextId);
169 }
170 }
171 return {
172 ...decodedFragment,
173 records: decodedFragment.records.filter((record) => pastedIds.has(record.contextId)),
174 };
176​
177/** Imports the same structured clipboard payload for focused paste and paste-to-focus. */
178export function importPastedComposerText(
179 clipboardData: Pick<DataTransfer, "getData">,
180 importContextFragment?: ComposerInlineTokenPasteOptions["importContextFragment"],
181): string {
182 const pastedText = clipboardData.getData("text/plain");
183 const fragment = importContextFragment ? readPastedComposerContext(clipboardData) : null;
184 const rewrittenIds =
185 fragment && fragment.records.length > 0 ? importContextFragment!(fragment) : null;
186 const text =
187 rewrittenIds && rewrittenIds.size > 0
188 ? replaceComposerContextReferences(pastedText, (occurrence) => {
189 const nextId = rewrittenIds.get(occurrence.contextId);
190 return nextId
191 ? formatComposerContextReference({
192 ...occurrence,
193 contextId: ComposerContextId.make(nextId),
194 kind: occurrence.kind === "element" ? "preview-annotation" : occurrence.kind,
195 })
196 : occurrence.source;
197 })
198 : pastedText;
199 return text;