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