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

terminal-links.ts

175 lines4.9 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​
12const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/g;
13const FILE_PATH_PATTERN =
14 /(?:~\/|\.{1,2}\/|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}/g;
15const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
16​
17function trimClosingDelimiters(value: string): string {
18 let output = value.replace(TRAILING_PUNCTUATION_PATTERN, "");
19 if (output.length === 0) return output;
20​
21 const trimUnbalanced = (open: string, close: string) => {
22 while (output.endsWith(close)) {
23 const opens = output.split(open).length - 1;
24 const closes = output.split(close).length - 1;
25 if (opens >= closes) return;
26 output = output.slice(0, -1);
27 }
28 };
29​
30 trimUnbalanced("(", ")");
31 trimUnbalanced("[", "]");
32 trimUnbalanced("{", "}");
33 return output;
35​
36function overlaps(a: { start: number; end: number }, b: { start: number; end: number }): boolean {
37 return a.start < b.end && b.start < a.end;
39​
40function collectMatches(
41 line: string,
42 kind: TerminalLinkKind,
43 pattern: RegExp,
44 existing: TerminalLinkMatch[],
45): TerminalLinkMatch[] {
46 const matches: TerminalLinkMatch[] = [];
47 pattern.lastIndex = 0;
48​
49 for (const rawMatch of line.matchAll(pattern)) {
50 const raw = rawMatch[0];
51 const start = rawMatch.index ?? -1;
52 if (start < 0 || raw.length === 0) continue;
53​
54 const trimmed = trimClosingDelimiters(raw);
55 if (trimmed.length === 0) continue;
56 if (kind === "path" && /^https?:\/\//i.test(trimmed)) continue;
57​
58 const candidate: TerminalLinkMatch = {
59 kind,
60 text: trimmed,
61 start,
62 end: start + trimmed.length,
63 };
64​
65 const collides = [...existing, ...matches].some((other) => overlaps(candidate, other));
66 if (collides) continue;
67​
68 matches.push(candidate);
69 }
70​
71 return matches;
73​
74function isWindowsAbsolutePath(value: string): boolean {
75 return /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("\\\\");
77​
78function isAbsolutePath(value: string): boolean {
79 return value.startsWith("/") || isWindowsAbsolutePath(value);
81​
82function isWindowsPathStyle(value: string): boolean {
83 return isWindowsAbsolutePath(value) || /[A-Za-z]:\\/.test(value);
85​
86function joinPath(base: string, next: string, separator: "/" | "\\"): string {
87 const cleanBase = base.replace(/[\\/]+$/, "");
88 if (separator === "\\") {
89 return `${cleanBase}\\${next.replaceAll("/", "\\")}`;
90 }
91 return `${cleanBase}/${next.replace(/^\/+/, "")}`;
93​
94function inferHomeFromCwd(cwd: string): string | undefined {
95 const posixUser = cwd.match(/^\/Users\/([^/]+)/);
96 if (posixUser?.[1]) {
97 return `/Users/${posixUser[1]}`;
98 }
99​
100 const posixHome = cwd.match(/^\/home\/([^/]+)/);
101 if (posixHome?.[1]) {
102 return `/home/${posixHome[1]}`;
103 }
104​
105 const windowsUser = cwd.match(/^([A-Za-z]:\\Users\\[^\\]+)/);
106 if (windowsUser?.[1]) {
107 return windowsUser[1];
108 }
109​
110 return undefined;
112​
113function splitPathAndPosition(value: string): {
114 path: string;
115 line: string | undefined;
116 column: string | undefined;
117} {
118 let path = value;
119 let column: string | undefined;
120 let line: string | undefined;
121​
122 const columnMatch = path.match(/:(\d+)$/);
123 if (!columnMatch?.[1]) {
124 return { path, line: undefined, column: undefined };
125 }
126​
127 column = columnMatch[1];
128 path = path.slice(0, -columnMatch[0].length);
129​
130 const lineMatch = path.match(/:(\d+)$/);
131 if (lineMatch?.[1]) {
132 line = lineMatch[1];
133 path = path.slice(0, -lineMatch[0].length);
134 } else {
135 line = column;
136 column = undefined;
137 }
138​
139 return { path, line, column };
141​
142export function extractTerminalLinks(line: string): TerminalLinkMatch[] {
143 const urlMatches = collectMatches(line, "url", URL_PATTERN, []);
144 const pathMatches = collectMatches(line, "path", FILE_PATH_PATTERN, urlMatches);
145 return [...urlMatches, ...pathMatches].toSorted((a, b) => a.start - b.start);
147​
148export function isTerminalLinkActivation(
149 event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
150 platform = typeof navigator === "undefined" ? "" : navigator.platform,
151): boolean {
152 if (platform.length === 0) return false;
153 return isMacPlatform(platform)
154 ? event.metaKey && !event.ctrlKey
155 : event.ctrlKey && !event.metaKey;
157​
158export function resolvePathLinkTarget(rawPath: string, cwd: string): string {
159 const { path, line, column } = splitPathAndPosition(rawPath);
160​
161 let resolvedPath = path;
162 if (path.startsWith("~/")) {
163 const home = inferHomeFromCwd(cwd);
164 if (home) {
165 const separator: "/" | "\\" = isWindowsPathStyle(home) ? "\\" : "/";
166 resolvedPath = joinPath(home, path.slice(2), separator);
167 }
168 } else if (!isAbsolutePath(path)) {
169 const separator: "/" | "\\" = isWindowsPathStyle(cwd) ? "\\" : "/";
170 resolvedPath = joinPath(cwd, path, separator);
171 }
172​
173 if (!line) return resolvedPath;
174 return `${resolvedPath}:${line}${column ? `:${column}` : ""}`;