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