Open History to see the last commit
1export type ComposerTriggerKind = "path" | "slash-command" | "slash-model";
2
3export interface ComposerTrigger {
4 kind: ComposerTriggerKind;
5 query: string;
6 rangeStart: number;
7 rangeEnd: number;
8}
9
10function clampCursor(text: string, cursor: number): number {
11 if (!Number.isFinite(cursor)) return text.length;
12 return Math.max(0, Math.min(text.length, Math.floor(cursor)));
13}
14
15function isWhitespace(char: string): boolean {
16 return char === " " || char === "\n" || char === "\t" || char === "\r";
17}
18
19function tokenStartForCursor(text: string, cursor: number): number {
20 let index = cursor - 1;
21 while (index >= 0 && !isWhitespace(text[index] ?? "")) {
22 index -= 1;
23 }
24 return index + 1;
25}
26
27export function detectComposerTrigger(text: string, cursorInput: number): ComposerTrigger | null {
28 const cursor = clampCursor(text, cursorInput);
29 const lineStart = text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1;
30 const linePrefix = text.slice(lineStart, cursor);
31
32 if (linePrefix.startsWith("/")) {
33 const commandMatch = /^\/(\S*)$/.exec(linePrefix);
34 if (commandMatch) {
35 const commandQuery = commandMatch[1] ?? "";
36 if (commandQuery.toLowerCase() === "model") {
37 return {
38 kind: "slash-model",
39 query: "",
40 rangeStart: lineStart,
41 rangeEnd: cursor,
42 };
43 }
44 if ("model".startsWith(commandQuery.toLowerCase())) {
45 return {
46 kind: "slash-command",
47 query: commandQuery,
48 rangeStart: lineStart,
49 rangeEnd: cursor,
50 };
51 }
52 return null;
53 }
54
55 const modelMatch = /^\/model(?:\s+(.*))?$/.exec(linePrefix);
56 if (modelMatch) {
57 return {
58 kind: "slash-model",
59 query: (modelMatch[1] ?? "").trim(),
60 rangeStart: lineStart,
61 rangeEnd: cursor,
62 };
63 }
64 }
65
66 const tokenStart = tokenStartForCursor(text, cursor);
67 const token = text.slice(tokenStart, cursor);
68 if (!token.startsWith("@")) {
69 return null;
70 }
71
72 return {
73 kind: "path",
74 query: token.slice(1),
75 rangeStart: tokenStart,
76 rangeEnd: cursor,
77 };
78}
79
80export function replaceTextRange(
81 text: string,
82 rangeStart: number,
83 rangeEnd: number,
84 replacement: string,
85): { text: string; cursor: number } {
86 const safeStart = Math.max(0, Math.min(text.length, rangeStart));
87 const safeEnd = Math.max(safeStart, Math.min(text.length, rangeEnd));
88 const nextText = `${text.slice(0, safeStart)}${replacement}${text.slice(safeEnd)}`;
89 return { text: nextText, cursor: safeStart + replacement.length };
90}