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

composer-logic.ts

302 lines8.7 KB

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