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

composerInlineTokens.ts

147 lines4.9 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​
102export function collectComposerInlineTokens(
103 text: string,
104 options: CollectComposerInlineTokensOptions = {},
105): ReadonlyArray<ComposerInlineToken> {
106 const matches = collectMentionTokens(text);
107​
108 for (const match of text.matchAll(SKILL_TOKEN_REGEX)) {
109 const fullMatch = match[0];
110 const prefix = match[1] ?? "";
111 const value = match[2] ?? "";
112 if (!value) {
113 continue;
114 }
115 const start = (match.index ?? 0) + prefix.length;
116 const end = start + fullMatch.length - prefix.length;
117 matches.push({
118 type: "skill",
119 value,
120 source: text.slice(start, end),
121 start,
122 end,
123 });
124 }
125​
126 for (const token of options.preserveTrailingFrom ?? []) {
127 if (
128 token.end === text.length &&
129 text.slice(token.start, token.end) === token.source &&
130 !matches.some(
131 (match) =>
132 match.type === token.type && match.start === token.start && match.end === token.end,
133 )
134 ) {
135 matches.push(token);
136 }
137 }
138​
139 // TeX can contain literal skill and file tokens, especially inside \text{}.
140 // They remain formula source rather than becoming composer context chips.
141 const math = matches.length > 0 ? markdownMathRanges(text) : [];
142 return matches
143 .filter(
144 (match) => !math.some((formula) => match.start < formula.end && match.end > formula.start),
145 )
146 .sort((left, right) => left.start - right.start);