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

composerInlineTokens.ts

174 lines6.0 KB

1import { markdownMathRanges } from "./markdownMath.ts";
2​
3export type ComposerInlineToken =
4 | {
5 readonly type: "mention";
6 readonly value: string;
7 readonly source: string;
8 readonly start: number;
9 readonly end: number;
10 }
11 | {
12 readonly type: "skill";
13 readonly value: string;
14 readonly source: string;
15 readonly start: number;
16 readonly end: number;
17 };
18​
19export interface CollectComposerInlineTokensOptions {
20 readonly preserveTrailingFrom?: ReadonlyArray<ComposerInlineToken>;
22​
23const SKILL_MENTION_SOURCE =
24 /(^|\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
25 .source;
26const SKILL_TOKEN_REGEX = new RegExp(`${SKILL_MENTION_SOURCE}(?=\\s)`, "gu");
27export const SKILL_MENTION_PATTERN = new RegExp(`${SKILL_MENTION_SOURCE}(?=\\s|$)`, "gu");
28const MENTION_TOKEN_REGEX = /(^|\s)@(?:"((?:\\.|[^"\\])*)"|([^\s@"]+))(?=\s)/g;
29/**
30 * Unbounded, every whitespace in the composer is a candidate start: the engine scans the rest
31 * of the text for a closing `]`, fails, and rescans from the next whitespace — quadratic on
32 * input like " [[[[[…". Only a basename ever survives the `label !== basename` check below, so
33 * this cannot reject a link a user could meaningfully write; the longest filename any common
34 * filesystem allows is 255.
35 */
36const MAX_FILE_LINK_LABEL_LENGTH = 512;
37const FILE_LINK_TOKEN_REGEX = new RegExp(
38 `(^|\\s)\\[((?:\\\\.|[^\\]\\\\]){0,${MAX_FILE_LINK_LABEL_LENGTH}})\\]\\(([^)\\s]+)\\)(?=\\s)`,
39 "g",
40);
41const URI_SCHEME_REGEX = /^[A-Za-z][A-Za-z0-9+.-]*:/;
42const WINDOWS_DRIVE_PATH_REGEX = /^[A-Za-z]:[\\/]/;
43const SCOPED_PACKAGE_REFERENCE_REGEX =
44 /^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*(?:\/[^\s@"]+)*$/;
45const DECORATOR_CALL_REFERENCE_REGEX = /^[\p{ID_Start}_$][\p{ID_Continue}.$\u200c\u200d]*\(/u;
46​
47function collectMentionTokens(text: string): ComposerInlineToken[] {
48 const matches: ComposerInlineToken[] = [];
49​
50 for (const match of text.matchAll(FILE_LINK_TOKEN_REGEX)) {
51 const fullMatch = match[0];
52 const prefix = match[1] ?? "";
53 const label = (match[2] ?? "").replace(/\\(.)/g, "$1");
54 const encodedPath = match[3] ?? "";
55 let path = encodedPath;
56 try {
57 path = decodeURIComponent(encodedPath);
58 } catch {}
59 const separatorIndex = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
60 const basename = separatorIndex >= 0 ? path.slice(separatorIndex + 1) : path;
61 const hasExternalScheme = URI_SCHEME_REGEX.test(path) && !WINDOWS_DRIVE_PATH_REGEX.test(path);
62 if (!path || hasExternalScheme || label !== basename) {
63 continue;
64 }
65 const start = (match.index ?? 0) + prefix.length;
66 const end = start + fullMatch.length - prefix.length;
67 matches.push({
68 type: "mention",
69 value: path,
70 source: text.slice(start, end),
71 start,
72 end,
73 });
74 }
75​
76 for (const match of text.matchAll(MENTION_TOKEN_REGEX)) {
77 const fullMatch = match[0];
78 const prefix = match[1] ?? "";
79 const quotedPath = match[2];
80 const path = quotedPath !== undefined ? quotedPath.replace(/\\(.)/g, "$1") : (match[3] ?? "");
81 if (
82 !path ||
83 (quotedPath === undefined &&
84 (SCOPED_PACKAGE_REFERENCE_REGEX.test(path) || DECORATOR_CALL_REFERENCE_REGEX.test(path)))
85 ) {
86 continue;
87 }
88 const start = (match.index ?? 0) + prefix.length;
89 const end = start + fullMatch.length - prefix.length;
90 matches.push({
91 type: "mention",
92 value: path,
93 source: text.slice(start, end),
94 start,
95 end,
96 });
97 }
98​
99 return matches;
101​
102/**
103 * Formulas in composer text, ignoring the `$` and `\[` that file names such as
104 * `posts.$postId.tsx` or `[id].tsx` put into a file link. File links are masked with letters,
105 * not spaces, so a link at the start of a line cannot become an indented code block.
106 * Bare `@path` mentions are not masked: one such as `@README.md$` can run into a formula's
107 * closing delimiter, and a mention written inside a real formula stays covered by it.
108 */
109export function composerMathRanges(
110 text: string,
111 mentions: ReadonlyArray<ComposerInlineToken> = collectMentionTokens(text),
112) {
113 let masked = text;
114 for (const mention of mentions) {
115 if (mention.type !== "mention" || !mention.source.startsWith("[")) continue;
116 masked =
117 masked.slice(0, mention.start) +
118 "x".repeat(mention.end - mention.start) +
119 masked.slice(mention.end);
120 }
121 return markdownMathRanges(masked).map(({ start, end }) => ({
122 start,
123 end,
124 source: text.slice(start, end),
125 }));
127​
128export function collectComposerInlineTokens(
129 text: string,
130 options: CollectComposerInlineTokensOptions = {},
131): ReadonlyArray<ComposerInlineToken> {
132 const matches = collectMentionTokens(text);
133​
134 for (const match of text.matchAll(SKILL_TOKEN_REGEX)) {
135 const fullMatch = match[0];
136 const prefix = match[1] ?? "";
137 const value = match[2] ?? "";
138 if (!value) {
139 continue;
140 }
141 const start = (match.index ?? 0) + prefix.length;
142 const end = start + fullMatch.length - prefix.length;
143 matches.push({
144 type: "skill",
145 value,
146 source: text.slice(start, end),
147 start,
148 end,
149 });
150 }
151​
152 for (const token of options.preserveTrailingFrom ?? []) {
153 if (
154 token.end === text.length &&
155 text.slice(token.start, token.end) === token.source &&
156 !matches.some(
157 (match) =>
158 match.type === token.type && match.start === token.start && match.end === token.end,
159 )
160 ) {
161 matches.push(token);
162 }
163 }
164​
165 // TeX can contain literal skill and file tokens, especially inside \text{}.
166 // They remain formula source rather than becoming composer context chips.
167 // Confirmed trailing file links are masked too, so a kept chip is not read as TeX.
168 const math = matches.length > 0 ? composerMathRanges(text, matches) : [];
169 return matches
170 .filter(
171 (match) => !math.some((formula) => match.start < formula.end && match.end > formula.start),
172 )
173 .sort((left, right) => left.start - right.start);