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

terminal-links.ts

266 lines7.5 KB

1import {
2 formatFilePathPosition,
3 splitFilePathPosition,
4} from "@t3tools/client-runtime/markdown-links";
5​
6import { isMacPlatform } from "./lib/utils";
7​
8export type TerminalLinkKind = "url" | "path";
9​
10export interface TerminalLinkMatch {
11 kind: TerminalLinkKind;
12 text: string;
13 start: number;
14 end: number;
16​
17export interface TerminalLinkBufferPosition {
18 x: number;
19 y: number;
21​
22export interface TerminalLinkBufferRange {
23 start: TerminalLinkBufferPosition;
24 end: TerminalLinkBufferPosition;
26​
27export interface TerminalBufferLineLike {
28 readonly isWrapped?: boolean;
29 translateToString(trimRight?: boolean): string;
31​
32export interface WrappedTerminalLinkLineSegment {
33 bufferLineNumber: number;
34 text: string;
35 startIndex: number;
36 endIndex: number;
38​
39export interface WrappedTerminalLinkLine {
40 text: string;
41 segments: ReadonlyArray<WrappedTerminalLinkLineSegment>;
43​
44const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/giu;
45const FILE_PATH_PATTERN =
46 /(?:~\/|\.{1,2}\/|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}/g;
47const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
48​
49function trimClosingDelimiters(value: string): string {
50 let output = value.replace(TRAILING_PUNCTUATION_PATTERN, "");
51 if (output.length === 0) return output;
52​
53 const trimUnbalanced = (open: string, close: string) => {
54 while (output.endsWith(close)) {
55 const opens = output.split(open).length - 1;
56 const closes = output.split(close).length - 1;
57 if (opens >= closes) return;
58 output = output.slice(0, -1);
59 }
60 };
61​
62 trimUnbalanced("(", ")");
63 trimUnbalanced("[", "]");
64 trimUnbalanced("{", "}");
65 return output;
67​
68function overlaps(a: { start: number; end: number }, b: { start: number; end: number }): boolean {
69 return a.start < b.end && b.start < a.end;
71​
72function collectMatches(
73 line: string,
74 kind: TerminalLinkKind,
75 pattern: RegExp,
76 existing: TerminalLinkMatch[],
77): TerminalLinkMatch[] {
78 const matches: TerminalLinkMatch[] = [];
79 pattern.lastIndex = 0;
80​
81 for (const rawMatch of line.matchAll(pattern)) {
82 const raw = rawMatch[0];
83 const start = rawMatch.index ?? -1;
84 if (start < 0 || raw.length === 0) continue;
85​
86 const trimmed = trimClosingDelimiters(raw);
87 if (trimmed.length === 0) continue;
88 if (kind === "path" && isTerminalUrl(trimmed)) continue;
89​
90 const candidate: TerminalLinkMatch = {
91 kind,
92 text: trimmed,
93 start,
94 end: start + trimmed.length,
95 };
96​
97 const collides = [...existing, ...matches].some((other) => overlaps(candidate, other));
98 if (collides) continue;
99​
100 matches.push(candidate);
101 }
102​
103 return matches;
105​
106function isWindowsAbsolutePath(value: string): boolean {
107 return /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("\\\\");
109​
110export function isAbsolutePath(value: string): boolean {
111 return value.startsWith("/") || isWindowsAbsolutePath(value);
113​
114function isWindowsPathStyle(value: string): boolean {
115 return isWindowsAbsolutePath(value) || /[A-Za-z]:\\/.test(value);
117​
118function joinPath(base: string, next: string, separator: "/" | "\\"): string {
119 const cleanBase = base.replace(/[\\/]+$/, "");
120 if (separator === "\\") {
121 return `${cleanBase}\\${next.replaceAll("/", "\\")}`;
122 }
123 return `${cleanBase}/${next.replace(/^\/+/, "")}`;
125​
126function inferHomeFromCwd(cwd: string): string | undefined {
127 const posixUser = cwd.match(/^\/Users\/([^/]+)/);
128 if (posixUser?.[1]) {
129 return `/Users/${posixUser[1]}`;
130 }
131​
132 const posixHome = cwd.match(/^\/home\/([^/]+)/);
133 if (posixHome?.[1]) {
134 return `/home/${posixHome[1]}`;
135 }
136​
137 const windowsUser = cwd.match(/^([A-Za-z]:\\Users\\[^\\]+)/);
138 if (windowsUser?.[1]) {
139 return windowsUser[1];
140 }
141​
142 return undefined;
144​
145export function extractTerminalLinks(line: string): TerminalLinkMatch[] {
146 const urlMatches = collectMatches(line, "url", URL_PATTERN, []);
147 const pathMatches = collectMatches(line, "path", FILE_PATH_PATTERN, urlMatches);
148 return [...urlMatches, ...pathMatches].toSorted((a, b) => a.start - b.start);
150​
151export function isTerminalUrl(value: string): boolean {
152 return /^https?:\/\//iu.test(value);
154​
155export function collectWrappedTerminalLinkLine(
156 bufferLineNumber: number,
157 getLine: (bufferLineIndex: number) => TerminalBufferLineLike | null | undefined,
158): WrappedTerminalLinkLine | null {
159 const anchorLine = getLine(bufferLineNumber - 1);
160 if (!anchorLine) return null;
161​
162 let startBufferLineNumber = bufferLineNumber;
163 let startLine = anchorLine;
164​
165 while (startBufferLineNumber > 1 && startLine.isWrapped) {
166 const previousLine = getLine(startBufferLineNumber - 2);
167 if (!previousLine) return null;
168 startBufferLineNumber -= 1;
169 startLine = previousLine;
170 }
171​
172 const segments: WrappedTerminalLinkLineSegment[] = [];
173 let nextStartIndex = 0;
174 let currentBufferLineNumber = startBufferLineNumber;
175​
176 while (true) {
177 const currentLine = getLine(currentBufferLineNumber - 1);
178 if (!currentLine) break;
179​
180 const nextLine = getLine(currentBufferLineNumber);
181 const hasWrappedContinuation = nextLine?.isWrapped === true;
182 const text = currentLine.translateToString(!hasWrappedContinuation);
183​
184 segments.push({
185 bufferLineNumber: currentBufferLineNumber,
186 text,
187 startIndex: nextStartIndex,
188 endIndex: nextStartIndex + text.length,
189 });
190 nextStartIndex += text.length;
191​
192 if (!hasWrappedContinuation) break;
193 currentBufferLineNumber += 1;
194 }
195​
196 return {
197 text: segments.map((segment) => segment.text).join(""),
198 segments,
199 };
201​
202function resolveCharacterPosition(
203 segments: ReadonlyArray<WrappedTerminalLinkLineSegment>,
204 characterIndex: number,
205): TerminalLinkBufferPosition {
206 for (const segment of segments) {
207 if (characterIndex < segment.endIndex) {
208 return {
209 x: characterIndex - segment.startIndex + 1,
210 y: segment.bufferLineNumber,
211 };
212 }
213 }
214​
215 const lastSegment = segments[segments.length - 1];
216 return {
217 x: Math.max(lastSegment?.text.length ?? 0, 1),
218 y: lastSegment?.bufferLineNumber ?? 1,
219 };
221​
222export function resolveWrappedTerminalLinkRange(
223 wrappedLine: WrappedTerminalLinkLine,
224 match: Pick<TerminalLinkMatch, "start" | "end">,
225): TerminalLinkBufferRange {
226 return {
227 start: resolveCharacterPosition(wrappedLine.segments, match.start),
228 end: resolveCharacterPosition(wrappedLine.segments, match.end - 1),
229 };
231​
232export function wrappedTerminalLinkRangeIntersectsBufferLine(
233 range: TerminalLinkBufferRange,
234 bufferLineNumber: number,
235): boolean {
236 return range.start.y <= bufferLineNumber && bufferLineNumber <= range.end.y;
238​
239export function isTerminalLinkActivation(
240 event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
241 platform = typeof navigator === "undefined" ? "" : navigator.platform,
242): boolean {
243 if (platform.length === 0) return false;
244 return isMacPlatform(platform)
245 ? event.metaKey && !event.ctrlKey
246 : event.ctrlKey && !event.metaKey;
248​
249export function resolvePathLinkTarget(rawPath: string, cwd: string): string {
250 const position = splitFilePathPosition(rawPath);
251 const { path } = position;
252​
253 let resolvedPath = path;
254 if (path.startsWith("~/")) {
255 const home = inferHomeFromCwd(cwd);
256 if (home) {
257 const separator: "/" | "\\" = isWindowsPathStyle(home) ? "\\" : "/";
258 resolvedPath = joinPath(home, path.slice(2), separator);
259 }
260 } else if (!isAbsolutePath(path)) {
261 const separator: "/" | "\\" = isWindowsPathStyle(cwd) ? "\\" : "/";
262 resolvedPath = joinPath(cwd, path, separator);
263 }
264​
265 return formatFilePathPosition({ ...position, path: resolvedPath });