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