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

composerInlineTokens.ts

133 lines4.4 KB

1export type ComposerInlineToken =
2 | {
3 readonly type: "mention";
4 readonly value: string;
5 readonly source: string;
6 readonly start: number;
7 readonly end: number;
8 }
9 | {
10 readonly type: "skill";
11 readonly value: string;
12 readonly source: string;
13 readonly start: number;
14 readonly end: number;
15 };
16​
17export interface CollectComposerInlineTokensOptions {
18 readonly preserveTrailingFrom?: ReadonlyArray<ComposerInlineToken>;
20​
21const SKILL_MENTION_SOURCE =
22 /(^|\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
23 .source;
24const SKILL_TOKEN_REGEX = new RegExp(`${SKILL_MENTION_SOURCE}(?=\\s)`, "gu");
25export const SKILL_MENTION_PATTERN = new RegExp(`${SKILL_MENTION_SOURCE}(?=\\s|$)`, "gu");
26const MENTION_TOKEN_REGEX = /(^|\s)@(?:"((?:\\.|[^"\\])*)"|([^\s@"]+))(?=\s)/g;
27/**
28 * Unbounded, every whitespace in the composer is a candidate start: the engine scans the rest
29 * of the text for a closing `]`, fails, and rescans from the next whitespace — quadratic on
30 * input like " [[[[[…". Only a basename ever survives the `label !== basename` check below, so
31 * this cannot reject a link a user could meaningfully write; the longest filename any common
32 * filesystem allows is 255.
33 */
34const MAX_FILE_LINK_LABEL_LENGTH = 512;
35const FILE_LINK_TOKEN_REGEX = new RegExp(
36 `(^|\\s)\\[((?:\\\\.|[^\\]\\\\]){0,${MAX_FILE_LINK_LABEL_LENGTH}})\\]\\(([^)\\s]+)\\)(?=\\s)`,
37 "g",
38);
39const URI_SCHEME_REGEX = /^[A-Za-z][A-Za-z0-9+.-]*:/;
40const WINDOWS_DRIVE_PATH_REGEX = /^[A-Za-z]:[\\/]/;
41const SCOPED_PACKAGE_REFERENCE_REGEX =
42 /^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*(?:\/[^\s@"]+)*$/;
43​
44function collectMentionTokens(text: string): ComposerInlineToken[] {
45 const matches: ComposerInlineToken[] = [];
46​
47 for (const match of text.matchAll(FILE_LINK_TOKEN_REGEX)) {
48 const fullMatch = match[0];
49 const prefix = match[1] ?? "";
50 const label = (match[2] ?? "").replace(/\\(.)/g, "$1");
51 const encodedPath = match[3] ?? "";
52 let path = encodedPath;
53 try {
54 path = decodeURIComponent(encodedPath);
55 } catch {}
56 const separatorIndex = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
57 const basename = separatorIndex >= 0 ? path.slice(separatorIndex + 1) : path;
58 const hasExternalScheme = URI_SCHEME_REGEX.test(path) && !WINDOWS_DRIVE_PATH_REGEX.test(path);
59 if (!path || hasExternalScheme || label !== basename) {
60 continue;
61 }
62 const start = (match.index ?? 0) + prefix.length;
63 const end = start + fullMatch.length - prefix.length;
64 matches.push({
65 type: "mention",
66 value: path,
67 source: text.slice(start, end),
68 start,
69 end,
70 });
71 }
72​
73 for (const match of text.matchAll(MENTION_TOKEN_REGEX)) {
74 const fullMatch = match[0];
75 const prefix = match[1] ?? "";
76 const quotedPath = match[2];
77 const path = quotedPath !== undefined ? quotedPath.replace(/\\(.)/g, "$1") : (match[3] ?? "");
78 if (!path || (quotedPath === undefined && SCOPED_PACKAGE_REFERENCE_REGEX.test(path))) {
79 continue;
80 }
81 const start = (match.index ?? 0) + prefix.length;
82 const end = start + fullMatch.length - prefix.length;
83 matches.push({
84 type: "mention",
85 value: path,
86 source: text.slice(start, end),
87 start,
88 end,
89 });
90 }
91​
92 return matches;
94​
95export function collectComposerInlineTokens(
96 text: string,
97 options: CollectComposerInlineTokensOptions = {},
98): ReadonlyArray<ComposerInlineToken> {
99 const matches = collectMentionTokens(text);
100​
101 for (const match of text.matchAll(SKILL_TOKEN_REGEX)) {
102 const fullMatch = match[0];
103 const prefix = match[1] ?? "";
104 const value = match[2] ?? "";
105 if (!value) {
106 continue;
107 }
108 const start = (match.index ?? 0) + prefix.length;
109 const end = start + fullMatch.length - prefix.length;
110 matches.push({
111 type: "skill",
112 value,
113 source: text.slice(start, end),
114 start,
115 end,
116 });
117 }
118​
119 for (const token of options.preserveTrailingFrom ?? []) {
120 if (
121 token.end === text.length &&
122 text.slice(token.start, token.end) === token.source &&
123 !matches.some(
124 (match) =>
125 match.type === token.type && match.start === token.start && match.end === token.end,
126 )
127 ) {
128 matches.push(token);
129 }
130 }
131​
132 return [...matches].sort((left, right) => left.start - right.start);