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

terminal-links.ts

196 lines6.8 KB

1import { isMacPlatform } from "./lib/utils";
2​
3export type TerminalLinkKind = "url" | "path";
4​
5export interface TerminalLinkMatch {
6 kind: TerminalLinkKind;
7 text: string;
8 start: number;
9 end: number;
11​
12export interface TerminalBufferLineLike {
13 readonly isWrapped?: boolean;
14 translateToString(trimRight?: boolean): string;
16​
17export interface WrappedTerminalLinkLineSegment {
18 bufferLineNumber: number;
19 text: string;
20 startIndex: number;
21 endIndex: number;
23​
24export interface WrappedTerminalLinkLine {
25 text: string;
26 segments: ReadonlyArray<WrappedTerminalLinkLineSegment>;
28​
29const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/giu;
30// The default PowerShell prompt delimits its unquoted path with `PS ` and `>`.
31const POWERSHELL_PROMPT_PATH_PATTERN = /^PS ((?:[A-Za-z]:[\\/]|\\\\|\/)[^>\r\n]*)>/u;
32// Bare paths start only at a segment boundary: hover detection runs this on
33// every frame, so separator-free output must not be rescanned at every suffix.
34const FILE_PATH_PATTERN =
35 /(?:~[\\/]|\.{1,2}[\\/]|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|(?<![\p{L}\p{M}\p{N}._-])[\p{L}\p{M}\p{N}._-]+(?:[\\/][\p{L}\p{M}\p{N}._-]+)+(?::\d+){0,2}/gu;
36const QUOTED_FILE_PATH_PATTERN =
37 /(["'`])(?<path>(?:~[\\/]|\.{1,2}[\\/]|\/|[A-Za-z]:[\\/]|\\\\|[\p{L}\p{M}\p{N}._ -]+[\\/])[^\r\n]*?|[\p{L}\p{M}\p{N}._ -]+\.[\p{L}\p{M}\p{N}_-]+(?::\d+){0,2})\1(?<position>(?::\d+){0,2})/gu;
38const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
39// Paths also drop a trailing colon: compilers end `file:line:col:` with one.
40const TRAILING_PATH_PUNCTUATION_PATTERN = /[.,;:!?]+$/;
41// A question mark is legal in filenames; only exclude query-bearing request targets.
42const REQUEST_ROUTE_PATTERN =
43 /(?:^|[\s"'`])(?:GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS|CONNECT|TRACE|proxying)\s+["'`]?(?:\/|[A-Za-z0-9_-]+\/)[^\s?]*\?\S*/g;
44// The tail of `redis://host/0` or `file:///a.mjs` is not a path. One-letter schemes stay drives,
45// a diff's `+` or `-` may lead, and the lookbehind keeps runs from being rescanned at every suffix.
46const SCHEME_URL_PATTERN = /(?<![A-Za-z\d+.-])[+-]?[A-Za-z][A-Za-z\d+.-]+:\/\/[^\s"'`<>]+/gu;
47​
48function trimClosingDelimiters(value: string, kind: TerminalLinkKind): string {
49 let output = value.replace(
50 kind === "path" ? TRAILING_PATH_PUNCTUATION_PATTERN : TRAILING_PUNCTUATION_PATTERN,
51 "",
52 );
53 if (output.length === 0) return output;
54​
55 const trimUnbalanced = (open: string, close: string) => {
56 while (output.endsWith(close)) {
57 const opens = output.split(open).length - 1;
58 const closes = output.split(close).length - 1;
59 if (opens >= closes) return;
60 output = output.slice(0, -1);
61 }
62 };
63​
64 trimUnbalanced("(", ")");
65 trimUnbalanced("[", "]");
66 trimUnbalanced("{", "}");
67 return output;
69​
70function overlaps(a: { start: number; end: number }, b: { start: number; end: number }): boolean {
71 return a.start < b.end && b.start < a.end;
73​
74function collectMatches(
75 line: string,
76 kind: TerminalLinkKind,
77 pattern: RegExp,
78 existing: TerminalLinkMatch[],
79): TerminalLinkMatch[] {
80 const matches: TerminalLinkMatch[] = [];
81 pattern.lastIndex = 0;
82​
83 for (const rawMatch of line.matchAll(pattern)) {
84 const quotedPath = rawMatch.groups?.path;
85 const raw =
86 quotedPath === undefined ? rawMatch[0] : quotedPath + (rawMatch.groups?.position ?? "");
87 const start = rawMatch.index + (quotedPath === undefined ? 0 : 1);
88 if (start < 0 || raw.length === 0) continue;
89​
90 const trimmed = quotedPath === undefined ? trimClosingDelimiters(raw, kind) : raw;
91 if (trimmed.length === 0) continue;
92 if (kind === "path" && isTerminalUrl(trimmed)) continue;
93​
94 const candidate: TerminalLinkMatch = {
95 kind,
96 text: trimmed,
97 start,
98 // A position outside quotes spans the closing quote in the terminal buffer.
99 end: start + trimmed.length + (rawMatch.groups?.position ? 1 : 0),
100 };
101​
102 const collides = [...existing, ...matches].some((other) => overlaps(candidate, other));
103 if (collides) continue;
104​
105 matches.push(candidate);
106 }
107​
108 return matches;
110​
111export function extractTerminalLinks(line: string): TerminalLinkMatch[] {
112 const promptPath = POWERSHELL_PROMPT_PATH_PATTERN.exec(line)?.[1];
113 const promptMatches: TerminalLinkMatch[] = promptPath
114 ? [{ kind: "path", text: promptPath, start: 3, end: 3 + promptPath.length }]
115 : [];
116 const nonPathRanges = Array.from(
117 [...line.matchAll(REQUEST_ROUTE_PATTERN), ...line.matchAll(SCHEME_URL_PATTERN)],
118 (match) => ({ start: match.index, end: match.index + match[0].length }),
119 );
120 const urlMatches = collectMatches(line, "url", URL_PATTERN, promptMatches);
121 const quotedMatches = collectMatches(line, "path", QUOTED_FILE_PATH_PATTERN, [
122 ...promptMatches,
123 ...urlMatches,
124 ]);
125 const pathMatches = collectMatches(line, "path", FILE_PATH_PATTERN, [
126 ...promptMatches,
127 ...urlMatches,
128 ...quotedMatches,
129 ]);
130 return [...promptMatches, ...urlMatches, ...quotedMatches, ...pathMatches]
131 .filter(
132 (match) => match.kind === "url" || !nonPathRanges.some((range) => overlaps(match, range)),
133 )
134 .toSorted((a, b) => a.start - b.start);
136​
137export function isTerminalUrl(value: string): boolean {
138 return /^https?:\/\//iu.test(value);
140​
141export function collectWrappedTerminalLinkLine(
142 bufferLineNumber: number,
143 getLine: (bufferLineIndex: number) => TerminalBufferLineLike | null | undefined,
144): WrappedTerminalLinkLine | null {
145 const anchorLine = getLine(bufferLineNumber - 1);
146 if (!anchorLine) return null;
147​
148 let startBufferLineNumber = bufferLineNumber;
149 let startLine = anchorLine;
150​
151 while (startBufferLineNumber > 1 && startLine.isWrapped) {
152 const previousLine = getLine(startBufferLineNumber - 2);
153 if (!previousLine) return null;
154 startBufferLineNumber -= 1;
155 startLine = previousLine;
156 }
157​
158 const segments: WrappedTerminalLinkLineSegment[] = [];
159 let nextStartIndex = 0;
160 let currentBufferLineNumber = startBufferLineNumber;
161​
162 while (true) {
163 const currentLine = getLine(currentBufferLineNumber - 1);
164 if (!currentLine) break;
165​
166 const nextLine = getLine(currentBufferLineNumber);
167 const hasWrappedContinuation = nextLine?.isWrapped === true;
168 const text = currentLine.translateToString(!hasWrappedContinuation);
169​
170 segments.push({
171 bufferLineNumber: currentBufferLineNumber,
172 text,
173 startIndex: nextStartIndex,
174 endIndex: nextStartIndex + text.length,
175 });
176 nextStartIndex += text.length;
177​
178 if (!hasWrappedContinuation) break;
179 currentBufferLineNumber += 1;
180 }
181​
182 return {
183 text: segments.map((segment) => segment.text).join(""),
184 segments,
185 };
187​
188export function isTerminalLinkActivation(
189 event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
190 platform = typeof navigator === "undefined" ? "" : navigator.platform,
191): boolean {
192 if (platform.length === 0) return false;
193 return isMacPlatform(platform)
194 ? event.metaKey && !event.ctrlKey
195 : event.ctrlKey && !event.metaKey;