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

composer-logic.ts

328 lines9.6 KB

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;
24​
25export function formatAssistantCitationForComposer(citation: AssistantCitation, comment = "") {
26 return `${serializeAssistantCitation(withAssistantCitationComment(citation, comment))} `;
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 );
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 === "composer.sendAndNewThread" && !input.isDraftThread) return "background";
63 if (command !== null || event.key !== "Enter" || event.shiftKey || event.altKey) return null;
64 if (
65 composerRequiresModifier(input.sendShortcut, input.prompt ?? "") &&
66 !event.metaKey &&
67 !event.ctrlKey
68 )
69 return null;
70 return "foreground";
72​
73const isInlineTokenSegment = (segment: ComposerPromptSegment): boolean => segment.type !== "text";
74​
75function clampCursor(text: string, cursor: number): number {
76 if (!Number.isFinite(cursor)) return text.length;
77 return Math.max(0, Math.min(text.length, Math.floor(cursor)));
79​
80function isWhitespace(char: string): boolean {
81 return char === " " || char === "\n" || char === "\t" || char === "\r";
83​
84function tokenStartForCursor(text: string, cursor: number): number {
85 let index = cursor - 1;
86 while (index >= 0 && !isWhitespace(text[index] ?? "")) {
87 index -= 1;
88 }
89 return index + 1;
91​
92export function expandCollapsedComposerCursor(text: string, cursorInput: number): number {
93 const collapsedCursor = clampCursor(text, cursorInput);
94 const segments = splitPromptIntoComposerSegments(text);
95 if (segments.length === 0) {
96 return collapsedCursor;
97 }
98​
99 let remaining = collapsedCursor;
100 let expandedCursor = 0;
101​
102 for (const segment of segments) {
103 if (
104 segment.type === "mention" ||
105 segment.type === "citation" ||
106 segment.type === "context-reference"
107 ) {
108 const expandedLength = segment.source.length;
109 if (remaining <= 1) {
110 return expandedCursor + (remaining === 0 ? 0 : expandedLength);
111 }
112 remaining -= 1;
113 expandedCursor += expandedLength;
114 continue;
115 }
116 if (segment.type === "skill") {
117 const expandedLength = segment.source.length;
118 if (remaining <= 1) {
119 return expandedCursor + (remaining === 0 ? 0 : expandedLength);
120 }
121 remaining -= 1;
122 expandedCursor += expandedLength;
123 continue;
124 }
125​
126 const segmentLength = segment.text.length;
127 if (remaining <= segmentLength) {
128 return expandedCursor + remaining;
129 }
130 remaining -= segmentLength;
131 expandedCursor += segmentLength;
132 }
133​
134 return expandedCursor;
136​
137function collapsedSegmentLength(segment: ComposerPromptSegment): number {
138 if (segment.type === "text") {
139 return segment.text.length;
140 }
141 return 1;
143​
144function clampCollapsedComposerCursorForSegments(
145 segments: ReadonlyArray<ComposerPromptSegment>,
146 cursorInput: number,
147): number {
148 const collapsedLength = segments.reduce(
149 (total, segment) => total + collapsedSegmentLength(segment),
150 0,
151 );
152 if (!Number.isFinite(cursorInput)) {
153 return collapsedLength;
154 }
155 return Math.max(0, Math.min(collapsedLength, Math.floor(cursorInput)));
157​
158export function clampCollapsedComposerCursor(text: string, cursorInput: number): number {
159 return clampCollapsedComposerCursorForSegments(
160 splitPromptIntoComposerSegments(text),
161 cursorInput,
162 );
164​
165export function collapseExpandedComposerCursor(text: string, cursorInput: number): number {
166 const expandedCursor = clampCursor(text, cursorInput);
167 const segments = splitPromptIntoComposerSegments(text);
168 if (segments.length === 0) {
169 return expandedCursor;
170 }
171​
172 let remaining = expandedCursor;
173 let collapsedCursor = 0;
174​
175 for (const segment of segments) {
176 if (
177 segment.type === "mention" ||
178 segment.type === "citation" ||
179 segment.type === "context-reference"
180 ) {
181 const expandedLength = segment.source.length;
182 if (remaining === 0) {
183 return collapsedCursor;
184 }
185 if (remaining <= expandedLength) {
186 return collapsedCursor + 1;
187 }
188 remaining -= expandedLength;
189 collapsedCursor += 1;
190 continue;
191 }
192 if (segment.type === "skill") {
193 const expandedLength = segment.source.length;
194 if (remaining === 0) {
195 return collapsedCursor;
196 }
197 if (remaining <= expandedLength) {
198 return collapsedCursor + 1;
199 }
200 remaining -= expandedLength;
201 collapsedCursor += 1;
202 continue;
203 }
204​
205 const segmentLength = segment.text.length;
206 if (remaining <= segmentLength) {
207 return collapsedCursor + remaining;
208 }
209 remaining -= segmentLength;
210 collapsedCursor += segmentLength;
211 }
212​
213 return collapsedCursor;
215​
216export function isCollapsedCursorAdjacentToInlineToken(
217 text: string,
218 cursorInput: number,
219 direction: "left" | "right",
220): boolean {
221 const segments = splitPromptIntoComposerSegments(text);
222 if (!segments.some(isInlineTokenSegment)) {
223 return false;
224 }
225​
226 const cursor = clampCollapsedComposerCursorForSegments(segments, cursorInput);
227 let collapsedOffset = 0;
228​
229 for (const segment of segments) {
230 if (isInlineTokenSegment(segment)) {
231 if (direction === "left" && cursor === collapsedOffset + 1) {
232 return true;
233 }
234 if (direction === "right" && cursor === collapsedOffset) {
235 return true;
236 }
237 }
238 collapsedOffset += collapsedSegmentLength(segment);
239 }
240​
241 return false;
243​
244export function detectComposerTrigger(text: string, cursorInput: number): ComposerTrigger | null {
245 const cursor = clampCursor(text, cursorInput);
246 const lineStart = text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1;
247 const linePrefix = text.slice(lineStart, cursor);
248​
249 if (linePrefix.startsWith("/")) {
250 const commandMatch = /^\/(\S*)$/.exec(linePrefix);
251 if (commandMatch) {
252 const commandQuery = commandMatch[1] ?? "";
253 return {
254 kind: "slash-command",
255 query: commandQuery,
256 rangeStart: lineStart,
257 rangeEnd: cursor,
258 };
259 }
260 }
261​
262 const tokenStart = tokenStartForCursor(text, cursor);
263 const token = text.slice(tokenStart, cursor);
264 const pullRequestMatch = /^#([\p{L}\p{N}][\p{L}\p{N}_-]*)?$/u.exec(token);
265 if (pullRequestMatch) {
266 return {
267 kind: "pull-request",
268 query: pullRequestMatch[1] ?? "",
269 rangeStart: tokenStart,
270 rangeEnd: cursor,
271 };
272 }
273 const skillPrefix = /^\p{Sc}/u.exec(token);
274 if (skillPrefix) {
275 return {
276 kind: "skill",
277 query: token.slice(skillPrefix[0].length),
278 rangeStart: tokenStart,
279 rangeEnd: cursor,
280 };
281 }
282 if (!token.startsWith("@")) {
283 return null;
284 }
285​
286 return {
287 kind: "path",
288 query: token.slice(1),
289 rangeStart: tokenStart,
290 rangeEnd: cursor,
291 };
293​
294/** Caret and trigger after replacing composer text and continuing at the end. */
295export function composerStateAtPromptEnd(text: string): {
296 cursor: number;
297 trigger: ComposerTrigger | null;
298} {
299 const cursor = collapseExpandedComposerCursor(text, text.length);
300 return {
301 cursor,
302 trigger: detectComposerTrigger(text, expandCollapsedComposerCursor(text, cursor)),
303 };
305​
306export function parseStandaloneComposerSlashCommand(
307 text: string,
308): Exclude<ComposerSlashCommand, "model"> | null {
309 const match = /^\/(plan|default)\s*$/i.exec(text.trim());
310 if (!match) {
311 return null;
312 }
313 const command = match[1]?.toLowerCase();
314 if (command === "plan") return "plan";
315 return "default";
317​
318export function replaceTextRange(
319 text: string,
320 rangeStart: number,
321 rangeEnd: number,
322 replacement: string,
323): { text: string; cursor: number } {
324 const safeStart = Math.max(0, Math.min(text.length, rangeStart));
325 const safeEnd = Math.max(safeStart, Math.min(text.length, rangeEnd));
326 const nextText = `${text.slice(0, safeStart)}${replacement}${text.slice(safeEnd)}`;
327 return { text: nextText, cursor: safeStart + replacement.length };