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

composerInlineTokens.ts

223 lines7.6 KB

1import { collectComposerContextReferences } from "./composerContextReferences.ts";
2import { composerFileLinkPath } from "./composerTrigger.ts";
3import { fileBasename } from "./path.ts";
4​
5/** The formulas a Markdown parser finds in text, as source offsets. */
6export type FindMathRanges = (
7 text: string,
8) => ReadonlyArray<{ readonly start: number; readonly end: number }>;
9​
10export type ComposerInlineToken =
11 | {
12 readonly type: "mention";
13 readonly value: string;
14 readonly source: string;
15 readonly start: number;
16 readonly end: number;
17 }
18 | {
19 readonly type: "skill";
20 readonly value: string;
21 readonly source: string;
22 readonly start: number;
23 readonly end: number;
24 };
25​
26export interface CollectComposerInlineTokensOptions {
27 readonly preserveTrailingFrom?: ReadonlyArray<ComposerInlineToken>;
28 /** Formulas keep their literal tokens; without it, nothing is read as math. */
29 readonly findMath?: FindMathRanges;
31​
32const SKILL_MENTION_SOURCE =
33 /(^|\s)\p{Sc}(?![0-9][0-9_]*(?:[kKmMbBtT]|[eE][0-9]+)?(?:\s|$))(?=[a-zA-Z0-9:_-]*[a-zA-Z])([a-zA-Z0-9][a-zA-Z0-9:_-]*)/u
34 .source;
35const SKILL_TOKEN_REGEX = new RegExp(`${SKILL_MENTION_SOURCE}(?=\\s)`, "gu");
36export const SKILL_MENTION_PATTERN = new RegExp(`${SKILL_MENTION_SOURCE}(?=\\s|$)`, "gu");
37const MENTION_TOKEN_REGEX = /(^|\s)@(?:"((?:\\.|[^"\\])*)"|([^\s@"]+))(?=\s)/g;
38// Bound unmatched-bracket rescans to avoid quadratic work; only basenames survive, and common filesystems cap them at 255.
39const MAX_FILE_LINK_LABEL_LENGTH = 512;
40const FILE_LINK_TOKEN_REGEX = new RegExp(
41 `(^|\\s)\\[((?:\\\\.|&#9[13];|&(?!#9[13];)|[^[\\]\\\\&]){0,${MAX_FILE_LINK_LABEL_LENGTH}})\\]\\(([^)\\s]+)\\)(?=\\s)`,
42 "g",
43);
44const URI_SCHEME_REGEX = /^[A-Za-z][A-Za-z0-9+.-]*:/;
45const WINDOWS_DRIVE_PATH_REGEX = /^[A-Za-z]:[\\/]/;
46const SCOPED_PACKAGE_REFERENCE_REGEX =
47 /^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*(?:\/[^\s@"]+)*$/;
48const DECORATOR_CALL_REFERENCE_REGEX = /^[\p{ID_Start}_$][\p{ID_Continue}.$\u200c\u200d]*\(/u;
49​
50function collectMentionTokens(text: string): ComposerInlineToken[] {
51 const matches: ComposerInlineToken[] = [];
52​
53 for (const match of text.matchAll(FILE_LINK_TOKEN_REGEX)) {
54 const fullMatch = match[0];
55 const prefix = match[1] ?? "";
56 const label = (match[2] ?? "").replace(
57 /\\(.)|&#9(1|3);/g,
58 (_match, escaped?: string, code?: string) => escaped ?? (code === "1" ? "[" : "]"),
59 );
60 const encodedPath = match[3] ?? "";
61 if (encodedPath.startsWith("//")) {
62 continue;
63 }
64 let path = encodedPath;
65 try {
66 path = decodeURIComponent(encodedPath);
67 } catch {}
68 const hasExternalScheme = URI_SCHEME_REGEX.test(path) && !WINDOWS_DRIVE_PATH_REGEX.test(path);
69 path = composerFileLinkPath(encodedPath, path);
70 const separatorIndex = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
71 const basename = separatorIndex >= 0 ? path.slice(separatorIndex + 1) : path;
72 if (!path || hasExternalScheme || label !== basename) {
73 continue;
74 }
75 const start = (match.index ?? 0) + prefix.length;
76 const end = start + fullMatch.length - prefix.length;
77 matches.push({
78 type: "mention",
79 value: path,
80 source: text.slice(start, end),
81 start,
82 end,
83 });
84 }
85​
86 for (const match of text.matchAll(MENTION_TOKEN_REGEX)) {
87 const fullMatch = match[0];
88 const prefix = match[1] ?? "";
89 const quotedPath = match[2];
90 const path =
91 quotedPath !== undefined ? quotedPath.replace(/\\(["\\])/g, "$1") : (match[3] ?? "");
92 if (
93 !path ||
94 (quotedPath === undefined &&
95 (SCOPED_PACKAGE_REFERENCE_REGEX.test(path) || DECORATOR_CALL_REFERENCE_REGEX.test(path)))
96 ) {
97 continue;
98 }
99 const start = (match.index ?? 0) + prefix.length;
100 const end = start + fullMatch.length - prefix.length;
101 matches.push({
102 type: "mention",
103 value: path,
104 source: text.slice(start, end),
105 start,
106 end,
107 });
108 }
109​
110 return matches;
112​
113/**
114 * Formulas in composer text, ignoring `$` and `\[` inside file links such as `posts.$postId.tsx`
115 * and `t3-context://` references. Links are masked with letters, not spaces, so a leading link
116 * cannot become an indented code block. Bare `@path` mentions stay unmasked so `@README.md$` can
117 * still close a formula.
118 */
119export function composerMathRanges(
120 text: string,
121 findMath: FindMathRanges,
122 mentions: ReadonlyArray<ComposerInlineToken> = collectMentionTokens(text),
123) {
124 const links = [
125 ...mentions.filter((mention) => mention.type === "mention" && mention.source.startsWith("[")),
126 ...collectComposerContextReferences(text),
127 ];
128 let masked = text;
129 for (const { start, end } of links) {
130 masked = masked.slice(0, start) + "x".repeat(end - start) + masked.slice(end);
131 }
132 return findMath(masked).map(({ start, end }) => ({
133 start,
134 end,
135 source: text.slice(start, end),
136 }));
138​
139export function collectComposerInlineTokens(
140 text: string,
141 options: CollectComposerInlineTokensOptions = {},
142): ReadonlyArray<ComposerInlineToken> {
143 const matches = collectMentionTokens(text);
144​
145 for (const match of text.matchAll(SKILL_TOKEN_REGEX)) {
146 const fullMatch = match[0];
147 const prefix = match[1] ?? "";
148 const value = match[2] ?? "";
149 if (!value) {
150 continue;
151 }
152 const start = (match.index ?? 0) + prefix.length;
153 const end = start + fullMatch.length - prefix.length;
154 matches.push({
155 type: "skill",
156 value,
157 source: text.slice(start, end),
158 start,
159 end,
160 });
161 }
162​
163 for (const token of options.preserveTrailingFrom ?? []) {
164 if (
165 token.end === text.length &&
166 text.slice(token.start, token.end) === token.source &&
167 !matches.some(
168 (match) =>
169 match.type === token.type && match.start === token.start && match.end === token.end,
170 )
171 ) {
172 matches.push(token);
173 }
174 }
175​
176 // TeX can contain literal skill and file tokens, especially inside \text{}.
177 // They remain formula source rather than becoming composer context chips.
178 // Confirmed trailing file links are masked too, so a kept chip is not read as TeX.
179 const math =
180 matches.length > 0 && options.findMath
181 ? composerMathRanges(text, options.findMath, matches)
182 : [];
183 const sorted = matches
184 .filter(
185 (match) => !math.some((formula) => match.start < formula.end && match.end > formula.start),
186 )
187 .sort((left, right) => left.start - right.start || right.end - left.end);
188 const resolved: ComposerInlineToken[] = [];
189 let cursor = 0;
190 for (const token of sorted) {
191 if (token.start < cursor) {
192 continue;
193 }
194 resolved.push(token);
195 cursor = token.end;
196 }
197 return resolved;
199​
200/**
201 * Sending trims the space that confirms a trailing chip, so a sent prompt reopened for editing
202 * gets it back. `collect` is the composer's own token reader, which waits for that space.
203 */
204export function restoreTrailingTokenSpace(
205 text: string,
206 collect: (text: string) => ReadonlyArray<{ readonly end: number }>,
207): string {
208 const endsInToken = (value: string) => collect(value).some((token) => token.end === text.length);
209 return !endsInToken(text) && endsInToken(`${text} `) ? `${text} ` : text;
211​
212/** Shows each `@`-file link by its file name, as its composer chip does, for one-line previews. */
213export function composerFileLinksToPlainText(text: string): string {
214 let result = "";
215 let cursor = 0;
216 // The composer reads a link as a mention only before whitespace, so one may end the text.
217 for (const token of collectMentionTokens(`${text} `)) {
218 if (!token.source.startsWith("[")) continue;
219 result += text.slice(cursor, token.start) + fileBasename(token.value);
220 cursor = token.end;
221 }
222 return result + text.slice(cursor);