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

terminal-links.ts

170 lines5.3 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;
30const FILE_PATH_PATTERN =
31 /(?:~[\\/]|\.{1,2}[\\/]|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|[A-Za-z0-9._-]+(?:[\\/][A-Za-z0-9._-]+)+(?::\d+){0,2}/g;
32const QUOTED_FILE_PATH_PATTERN =
33 /(["'`])(?<path>(?:~[\\/]|\.{1,2}[\\/]|\/|[A-Za-z]:[\\/]|\\\\|[A-Za-z0-9._ -]+[\\/])[^\r\n]*?|[A-Za-z0-9._ -]+\.[A-Za-z0-9_-]+(?::\d+){0,2})\1(?<position>(?::\d+){0,2})/g;
34const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
35// Paths also drop a trailing colon: compilers end `file:line:col:` with one.
36const TRAILING_PATH_PUNCTUATION_PATTERN = /[.,;:!?]+$/;
37​
38function trimClosingDelimiters(value: string, kind: TerminalLinkKind): string {
39 let output = value.replace(
40 kind === "path" ? TRAILING_PATH_PUNCTUATION_PATTERN : TRAILING_PUNCTUATION_PATTERN,
41 "",
42 );
43 if (output.length === 0) return output;
44​
45 const trimUnbalanced = (open: string, close: string) => {
46 while (output.endsWith(close)) {
47 const opens = output.split(open).length - 1;
48 const closes = output.split(close).length - 1;
49 if (opens >= closes) return;
50 output = output.slice(0, -1);
51 }
52 };
53​
54 trimUnbalanced("(", ")");
55 trimUnbalanced("[", "]");
56 trimUnbalanced("{", "}");
57 return output;
59​
60function overlaps(a: { start: number; end: number }, b: { start: number; end: number }): boolean {
61 return a.start < b.end && b.start < a.end;
63​
64function collectMatches(
65 line: string,
66 kind: TerminalLinkKind,
67 pattern: RegExp,
68 existing: TerminalLinkMatch[],
69): TerminalLinkMatch[] {
70 const matches: TerminalLinkMatch[] = [];
71 pattern.lastIndex = 0;
72​
73 for (const rawMatch of line.matchAll(pattern)) {
74 const quotedPath = rawMatch.groups?.path;
75 const raw =
76 quotedPath === undefined ? rawMatch[0] : quotedPath + (rawMatch.groups?.position ?? "");
77 const start = rawMatch.index + (quotedPath === undefined ? 0 : 1);
78 if (start < 0 || raw.length === 0) continue;
79​
80 const trimmed = quotedPath === undefined ? trimClosingDelimiters(raw, kind) : raw;
81 if (trimmed.length === 0) continue;
82 if (kind === "path" && isTerminalUrl(trimmed)) continue;
83​
84 const candidate: TerminalLinkMatch = {
85 kind,
86 text: trimmed,
87 start,
88 // A position outside quotes spans the closing quote in the terminal buffer.
89 end: start + trimmed.length + (rawMatch.groups?.position ? 1 : 0),
90 };
91​
92 const collides = [...existing, ...matches].some((other) => overlaps(candidate, other));
93 if (collides) continue;
94​
95 matches.push(candidate);
96 }
97​
98 return matches;
100​
101export function extractTerminalLinks(line: string): TerminalLinkMatch[] {
102 const urlMatches = collectMatches(line, "url", URL_PATTERN, []);
103 const quotedMatches = collectMatches(line, "path", QUOTED_FILE_PATH_PATTERN, urlMatches);
104 const pathMatches = collectMatches(line, "path", FILE_PATH_PATTERN, [
105 ...urlMatches,
106 ...quotedMatches,
107 ]);
108 return [...urlMatches, ...quotedMatches, ...pathMatches].toSorted((a, b) => a.start - b.start);
110​
111export function isTerminalUrl(value: string): boolean {
112 return /^https?:\/\//iu.test(value);
114​
115export function collectWrappedTerminalLinkLine(
116 bufferLineNumber: number,
117 getLine: (bufferLineIndex: number) => TerminalBufferLineLike | null | undefined,
118): WrappedTerminalLinkLine | null {
119 const anchorLine = getLine(bufferLineNumber - 1);
120 if (!anchorLine) return null;
121​
122 let startBufferLineNumber = bufferLineNumber;
123 let startLine = anchorLine;
124​
125 while (startBufferLineNumber > 1 && startLine.isWrapped) {
126 const previousLine = getLine(startBufferLineNumber - 2);
127 if (!previousLine) return null;
128 startBufferLineNumber -= 1;
129 startLine = previousLine;
130 }
131​
132 const segments: WrappedTerminalLinkLineSegment[] = [];
133 let nextStartIndex = 0;
134 let currentBufferLineNumber = startBufferLineNumber;
135​
136 while (true) {
137 const currentLine = getLine(currentBufferLineNumber - 1);
138 if (!currentLine) break;
139​
140 const nextLine = getLine(currentBufferLineNumber);
141 const hasWrappedContinuation = nextLine?.isWrapped === true;
142 const text = currentLine.translateToString(!hasWrappedContinuation);
143​
144 segments.push({
145 bufferLineNumber: currentBufferLineNumber,
146 text,
147 startIndex: nextStartIndex,
148 endIndex: nextStartIndex + text.length,
149 });
150 nextStartIndex += text.length;
151​
152 if (!hasWrappedContinuation) break;
153 currentBufferLineNumber += 1;
154 }
155​
156 return {
157 text: segments.map((segment) => segment.text).join(""),
158 segments,
159 };
161​
162export function isTerminalLinkActivation(
163 event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
164 platform = typeof navigator === "undefined" ? "" : navigator.platform,
165): boolean {
166 if (platform.length === 0) return false;
167 return isMacPlatform(platform)
168 ? event.metaKey && !event.ctrlKey
169 : event.ctrlKey && !event.metaKey;