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