Open History to see the last commit
1import type { ClientSettings } from "@t3tools/contracts/settings";
2import type { AssistantCitation, ResolvedKeybindingsConfig } from "@t3tools/contracts";
3import {
4 serializeAssistantCitation,
5 withAssistantCitationComment,
6} from "@t3tools/shared/assistantCitations";
7import {
8 splitPromptIntoComposerSegments,
9 type ComposerPromptSegment,
10} from "./composer-editor-mentions";
11
12import { resolveShortcutCommand, type ShortcutEventLike } from "./keybindings";
13
14export type ComposerTriggerKind = "path" | "pull-request" | "slash-command" | "skill";
15export type ComposerSlashCommand = "model" | "plan" | "default";
16export type ComposerSubmissionIntent = "foreground" | "background" | "alternate";
17
18export interface ComposerTrigger {
19 kind: ComposerTriggerKind;
20 query: string;
21 rangeStart: number;
22 rangeEnd: number;
23}
24
25export function formatAssistantCitationForComposer(citation: AssistantCitation, comment = "") {
26 return `${serializeAssistantCitation(withAssistantCitationComment(citation, comment))} `;
27}
28
29function composerRequiresModifier(
30 sendShortcut: ClientSettings["sendShortcut"] | undefined,
31 prompt: string,
32) {
33 return (
34 sendShortcut === "mod-enter" ||
35 (sendShortcut === "mod-enter-multiline" && /[\r\n]/.test(prompt))
36 );
37}
38
39export function composerSubmissionIntentForKey(input: {
40 event: ShortcutEventLike & { isComposing?: boolean; keyCode?: number; repeat?: boolean };
41 keybindings: ResolvedKeybindingsConfig;
42 platform?: string;
43 isMobileViewport: boolean;
44 isDraftThread: boolean;
45 isRunning?: boolean;
46 sendShortcut?: ClientSettings["sendShortcut"];
47 prompt?: string;
48}): ComposerSubmissionIntent | null {
49 const { event } = input;
50 if (input.isMobileViewport || event.isComposing || event.keyCode === 229 || event.repeat)
51 return null;
52 const command = resolveShortcutCommand(event, input.keybindings, {
53 ...(input.platform === undefined ? {} : { platform: input.platform }),
54 context: {
55 composerFocus: true,
56 draftThreadRoute: input.isDraftThread,
57 turnRunning: input.isRunning === true,
58 },
59 });
60 if (command === "composer.sendAlternate" && input.isRunning) return "alternate";
61 if (command === "composer.sendBackground" && input.isDraftThread) return "background";
62 if (command !== null || event.key !== "Enter" || event.shiftKey || event.altKey) return null;
63 if (
64 composerRequiresModifier(input.sendShortcut, input.prompt ?? "") &&
65 !event.metaKey &&
66 !event.ctrlKey
67 )
68 return null;
69 return "foreground";
70}
71
72const isInlineTokenSegment = (segment: ComposerPromptSegment): boolean => segment.type !== "text";
73
74function clampCursor(text: string, cursor: number): number {
75 if (!Number.isFinite(cursor)) return text.length;
76 return Math.max(0, Math.min(text.length, Math.floor(cursor)));
77}
78
79function isWhitespace(char: string): boolean {
80 return char === " " || char === "\n" || char === "\t" || char === "\r";
81}
82
83function tokenStartForCursor(text: string, cursor: number): number {
84 let index = cursor - 1;
85 while (index >= 0 && !isWhitespace(text[index] ?? "")) {
86 index -= 1;
87 }
88 return index + 1;
89}
90
91export function expandCollapsedComposerCursor(text: string, cursorInput: number): number {
92 const collapsedCursor = clampCursor(text, cursorInput);
93 const segments = splitPromptIntoComposerSegments(text);
94 if (segments.length === 0) {
95 return collapsedCursor;
96 }
97
98 let remaining = collapsedCursor;
99 let expandedCursor = 0;
100
101 for (const segment of segments) {
102 if (
103 segment.type === "mention" ||
104 segment.type === "citation" ||
105 segment.type === "context-reference"
106 ) {
107 const expandedLength = segment.source.length;
108 if (remaining <= 1) {
109 return expandedCursor + (remaining === 0 ? 0 : expandedLength);
110 }
111 remaining -= 1;
112 expandedCursor += expandedLength;
113 continue;
114 }
115 if (segment.type === "skill") {
116 const expandedLength = segment.source.length;
117 if (remaining <= 1) {
118 return expandedCursor + (remaining === 0 ? 0 : expandedLength);
119 }
120 remaining -= 1;
121 expandedCursor += expandedLength;
122 continue;
123 }
124
125 const segmentLength = segment.text.length;
126 if (remaining <= segmentLength) {
127 return expandedCursor + remaining;
128 }
129 remaining -= segmentLength;
130 expandedCursor += segmentLength;
131 }
132
133 return expandedCursor;
134}
135
136function collapsedSegmentLength(segment: ComposerPromptSegment): number {
137 if (segment.type === "text") {
138 return segment.text.length;
139 }
140 return 1;
141}
142
143function clampCollapsedComposerCursorForSegments(
144 segments: ReadonlyArray<ComposerPromptSegment>,
145 cursorInput: number,
146): number {
147 const collapsedLength = segments.reduce(
148 (total, segment) => total + collapsedSegmentLength(segment),
149 0,
150 );
151 if (!Number.isFinite(cursorInput)) {
152 return collapsedLength;
153 }
154 return Math.max(0, Math.min(collapsedLength, Math.floor(cursorInput)));
155}
156
157export function clampCollapsedComposerCursor(text: string, cursorInput: number): number {
158 return clampCollapsedComposerCursorForSegments(
159 splitPromptIntoComposerSegments(text),
160 cursorInput,
161 );
162}
163
164export function collapseExpandedComposerCursor(text: string, cursorInput: number): number {
165 const expandedCursor = clampCursor(text, cursorInput);
166 const segments = splitPromptIntoComposerSegments(text);
167 if (segments.length === 0) {
168 return expandedCursor;
169 }
170
171 let remaining = expandedCursor;
172 let collapsedCursor = 0;
173
174 for (const segment of segments) {
175 if (
176 segment.type === "mention" ||
177 segment.type === "citation" ||
178 segment.type === "context-reference"
179 ) {
180 const expandedLength = segment.source.length;
181 if (remaining === 0) {
182 return collapsedCursor;
183 }
184 if (remaining <= expandedLength) {
185 return collapsedCursor + 1;
186 }
187 remaining -= expandedLength;
188 collapsedCursor += 1;
189 continue;
190 }
191 if (segment.type === "skill") {
192 const expandedLength = segment.source.length;
193 if (remaining === 0) {
194 return collapsedCursor;
195 }
196 if (remaining <= expandedLength) {
197 return collapsedCursor + 1;
198 }
199 remaining -= expandedLength;
200 collapsedCursor += 1;
201 continue;
202 }
203
204 const segmentLength = segment.text.length;
205 if (remaining <= segmentLength) {
206 return collapsedCursor + remaining;
207 }
208 remaining -= segmentLength;
209 collapsedCursor += segmentLength;
210 }
211
212 return collapsedCursor;
213}
214
215export function isCollapsedCursorAdjacentToInlineToken(
216 text: string,
217 cursorInput: number,
218 direction: "left" | "right",
219): boolean {
220 const segments = splitPromptIntoComposerSegments(text);
221 if (!segments.some(isInlineTokenSegment)) {
222 return false;
223 }
224
225 const cursor = clampCollapsedComposerCursorForSegments(segments, cursorInput);
226 let collapsedOffset = 0;
227
228 for (const segment of segments) {
229 if (isInlineTokenSegment(segment)) {
230 if (direction === "left" && cursor === collapsedOffset + 1) {
231 return true;
232 }
233 if (direction === "right" && cursor === collapsedOffset) {
234 return true;
235 }
236 }
237 collapsedOffset += collapsedSegmentLength(segment);
238 }
239
240 return false;
241}
242
243export function detectComposerTrigger(text: string, cursorInput: number): ComposerTrigger | null {
244 const cursor = clampCursor(text, cursorInput);
245 const lineStart = text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1;
246 const linePrefix = text.slice(lineStart, cursor);
247
248 if (linePrefix.startsWith("/")) {
249 const commandMatch = /^\/(\S*)$/.exec(linePrefix);
250 if (commandMatch) {
251 const commandQuery = commandMatch[1] ?? "";
252 return {
253 kind: "slash-command",
254 query: commandQuery,
255 rangeStart: lineStart,
256 rangeEnd: cursor,
257 };
258 }
259 }
260
261 const tokenStart = tokenStartForCursor(text, cursor);
262 const token = text.slice(tokenStart, cursor);
263 const pullRequestMatch = /^#([\p{L}\p{N}][\p{L}\p{N}_-]*)?$/u.exec(token);
264 if (pullRequestMatch) {
265 return {
266 kind: "pull-request",
267 query: pullRequestMatch[1] ?? "",
268 rangeStart: tokenStart,
269 rangeEnd: cursor,
270 };
271 }
272 const skillPrefix = /^\p{Sc}/u.exec(token);
273 if (skillPrefix) {
274 return {
275 kind: "skill",
276 query: token.slice(skillPrefix[0].length),
277 rangeStart: tokenStart,
278 rangeEnd: cursor,
279 };
280 }
281 if (!token.startsWith("@")) {
282 return null;
283 }
284
285 return {
286 kind: "path",
287 query: token.slice(1),
288 rangeStart: tokenStart,
289 rangeEnd: cursor,
290 };
291}
292
293/** Caret and trigger after replacing composer text and continuing at the end. */
294export function composerStateAtPromptEnd(text: string): {
295 cursor: number;
296 trigger: ComposerTrigger | null;
297} {
298 const cursor = collapseExpandedComposerCursor(text, text.length);
299 return {
300 cursor,
301 trigger: detectComposerTrigger(text, expandCollapsedComposerCursor(text, cursor)),
302 };
303}
304
305export function parseStandaloneComposerSlashCommand(
306 text: string,
307): Exclude<ComposerSlashCommand, "model"> | null {
308 const match = /^\/(plan|default)\s*$/i.exec(text.trim());
309 if (!match) {
310 return null;
311 }
312 const command = match[1]?.toLowerCase();
313 if (command === "plan") return "plan";
314 return "default";
315}
316
317export function replaceTextRange(
318 text: string,
319 rangeStart: number,
320 rangeEnd: number,
321 replacement: string,
322): { text: string; cursor: number } {
323 const safeStart = Math.max(0, Math.min(text.length, rangeStart));
324 const safeEnd = Math.max(safeStart, Math.min(text.length, rangeEnd));
325 const nextText = `${text.slice(0, safeStart)}${replacement}${text.slice(safeEnd)}`;
326 return { text: nextText, cursor: safeStart + replacement.length };
327}