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

composerInlineTokens.ts

194 lines6.7 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)\\[((?:\\\\.|[^[\\]\\\\]){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(/\\(.)/g, "$1");
57 const encodedPath = match[3] ?? "";
58 let path = encodedPath;
59 try {
60 path = decodeURIComponent(encodedPath);
61 } catch {}
62 path = composerFileLinkPath(encodedPath, path);
63 const separatorIndex = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
64 const basename = separatorIndex >= 0 ? path.slice(separatorIndex + 1) : path;
65 const hasExternalScheme = URI_SCHEME_REGEX.test(path) && !WINDOWS_DRIVE_PATH_REGEX.test(path);
66 if (!path || hasExternalScheme || label !== basename) {
67 continue;
68 }
69 const start = (match.index ?? 0) + prefix.length;
70 const end = start + fullMatch.length - prefix.length;
71 matches.push({
72 type: "mention",
73 value: path,
74 source: text.slice(start, end),
75 start,
76 end,
77 });
78 }
79​
80 for (const match of text.matchAll(MENTION_TOKEN_REGEX)) {
81 const fullMatch = match[0];
82 const prefix = match[1] ?? "";
83 const quotedPath = match[2];
84 const path = quotedPath !== undefined ? quotedPath.replace(/\\(.)/g, "$1") : (match[3] ?? "");
85 if (
86 !path ||
87 (quotedPath === undefined &&
88 (SCOPED_PACKAGE_REFERENCE_REGEX.test(path) || DECORATOR_CALL_REFERENCE_REGEX.test(path)))
89 ) {
90 continue;
91 }
92 const start = (match.index ?? 0) + prefix.length;
93 const end = start + fullMatch.length - prefix.length;
94 matches.push({
95 type: "mention",
96 value: path,
97 source: text.slice(start, end),
98 start,
99 end,
100 });
101 }
102​
103 return matches;
105​
106/**
107 * Formulas in composer text, ignoring `$` and `\[` inside file links such as `posts.$postId.tsx`
108 * and `t3-context://` references. Links are masked with letters, not spaces, so a leading link
109 * cannot become an indented code block. Bare `@path` mentions stay unmasked so `@README.md$` can
110 * still close a formula.
111 */
112export function composerMathRanges(
113 text: string,
114 findMath: FindMathRanges,
115 mentions: ReadonlyArray<ComposerInlineToken> = collectMentionTokens(text),
116) {
117 const links = [
118 ...mentions.filter((mention) => mention.type === "mention" && mention.source.startsWith("[")),
119 ...collectComposerContextReferences(text),
120 ];
121 let masked = text;
122 for (const { start, end } of links) {
123 masked = masked.slice(0, start) + "x".repeat(end - start) + masked.slice(end);
124 }
125 return findMath(masked).map(({ start, end }) => ({
126 start,
127 end,
128 source: text.slice(start, end),
129 }));
131​
132export function collectComposerInlineTokens(
133 text: string,
134 options: CollectComposerInlineTokensOptions = {},
135): ReadonlyArray<ComposerInlineToken> {
136 const matches = collectMentionTokens(text);
137​
138 for (const match of text.matchAll(SKILL_TOKEN_REGEX)) {
139 const fullMatch = match[0];
140 const prefix = match[1] ?? "";
141 const value = match[2] ?? "";
142 if (!value) {
143 continue;
144 }
145 const start = (match.index ?? 0) + prefix.length;
146 const end = start + fullMatch.length - prefix.length;
147 matches.push({
148 type: "skill",
149 value,
150 source: text.slice(start, end),
151 start,
152 end,
153 });
154 }
155​
156 for (const token of options.preserveTrailingFrom ?? []) {
157 if (
158 token.end === text.length &&
159 text.slice(token.start, token.end) === token.source &&
160 !matches.some(
161 (match) =>
162 match.type === token.type && match.start === token.start && match.end === token.end,
163 )
164 ) {
165 matches.push(token);
166 }
167 }
168​
169 // TeX can contain literal skill and file tokens, especially inside \text{}.
170 // They remain formula source rather than becoming composer context chips.
171 // Confirmed trailing file links are masked too, so a kept chip is not read as TeX.
172 const math =
173 matches.length > 0 && options.findMath
174 ? composerMathRanges(text, options.findMath, matches)
175 : [];
176 return matches
177 .filter(
178 (match) => !math.some((formula) => match.start < formula.end && match.end > formula.start),
179 )
180 .sort((left, right) => left.start - right.start);
182​
183/** Shows each `@`-file link by its file name, as its composer chip does, for one-line previews. */
184export function composerFileLinksToPlainText(text: string): string {
185 let result = "";
186 let cursor = 0;
187 // The composer reads a link as a mention only before whitespace, so one may end the text.
188 for (const token of collectMentionTokens(`${text} `)) {
189 if (!token.source.startsWith("[")) continue;
190 result += text.slice(cursor, token.start) + fileBasename(token.value);
191 cursor = token.end;
192 }
193 return result + text.slice(cursor);