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

terminal-links.ts

224 lines6.4 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 TerminalBufferLineLike {
18 readonly isWrapped?: boolean;
19 translateToString(trimRight?: boolean): string;
21​
22export interface WrappedTerminalLinkLineSegment {
23 bufferLineNumber: number;
24 text: string;
25 startIndex: number;
26 endIndex: number;
28​
29export interface WrappedTerminalLinkLine {
30 text: string;
31 segments: ReadonlyArray<WrappedTerminalLinkLineSegment>;
33​
34const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/giu;
35const FILE_PATH_PATTERN =
36 /(?:~\/|\.{1,2}\/|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}/g;
37const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
38// Paths also drop a trailing colon: compilers end `file:line:col:` with one.
39const TRAILING_PATH_PUNCTUATION_PATTERN = /[.,;:!?]+$/;
40​
41function trimClosingDelimiters(value: string, kind: TerminalLinkKind): string {
42 let output = value.replace(
43 kind === "path" ? TRAILING_PATH_PUNCTUATION_PATTERN : TRAILING_PUNCTUATION_PATTERN,
44 "",
45 );
46 if (output.length === 0) return output;
47​
48 const trimUnbalanced = (open: string, close: string) => {
49 while (output.endsWith(close)) {
50 const opens = output.split(open).length - 1;
51 const closes = output.split(close).length - 1;
52 if (opens >= closes) return;
53 output = output.slice(0, -1);
54 }
55 };
56​
57 trimUnbalanced("(", ")");
58 trimUnbalanced("[", "]");
59 trimUnbalanced("{", "}");
60 return output;
62​
63function overlaps(a: { start: number; end: number }, b: { start: number; end: number }): boolean {
64 return a.start < b.end && b.start < a.end;
66​
67function collectMatches(
68 line: string,
69 kind: TerminalLinkKind,
70 pattern: RegExp,
71 existing: TerminalLinkMatch[],
72): TerminalLinkMatch[] {
73 const matches: TerminalLinkMatch[] = [];
74 pattern.lastIndex = 0;
75​
76 for (const rawMatch of line.matchAll(pattern)) {
77 const raw = rawMatch[0];
78 const start = rawMatch.index ?? -1;
79 if (start < 0 || raw.length === 0) continue;
80​
81 const trimmed = trimClosingDelimiters(raw, kind);
82 if (trimmed.length === 0) continue;
83 if (kind === "path" && isTerminalUrl(trimmed)) continue;
84​
85 const candidate: TerminalLinkMatch = {
86 kind,
87 text: trimmed,
88 start,
89 end: start + trimmed.length,
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​
101function isWindowsAbsolutePath(value: string): boolean {
102 return /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("\\\\");
104​
105export function isAbsolutePath(value: string): boolean {
106 return value.startsWith("/") || isWindowsAbsolutePath(value);
108​
109function isWindowsPathStyle(value: string): boolean {
110 return isWindowsAbsolutePath(value) || /[A-Za-z]:\\/.test(value);
112​
113function joinPath(base: string, next: string, separator: "/" | "\\"): string {
114 const cleanBase = base.replace(/[\\/]+$/, "");
115 if (separator === "\\") {
116 return `${cleanBase}\\${next.replaceAll("/", "\\")}`;
117 }
118 return `${cleanBase}/${next.replace(/^\/+/, "")}`;
120​
121function inferHomeFromCwd(cwd: string): string | undefined {
122 const posixUser = cwd.match(/^\/Users\/([^/]+)/);
123 if (posixUser?.[1]) {
124 return `/Users/${posixUser[1]}`;
125 }
126​
127 const posixHome = cwd.match(/^\/home\/([^/]+)/);
128 if (posixHome?.[1]) {
129 return `/home/${posixHome[1]}`;
130 }
131​
132 const windowsUser = cwd.match(/^([A-Za-z]:\\Users\\[^\\]+)/);
133 if (windowsUser?.[1]) {
134 return windowsUser[1];
135 }
136​
137 return undefined;
139​
140export function extractTerminalLinks(line: string): TerminalLinkMatch[] {
141 const urlMatches = collectMatches(line, "url", URL_PATTERN, []);
142 const pathMatches = collectMatches(line, "path", FILE_PATH_PATTERN, urlMatches);
143 return [...urlMatches, ...pathMatches].toSorted((a, b) => a.start - b.start);
145​
146export function isTerminalUrl(value: string): boolean {
147 return /^https?:\/\//iu.test(value);
149​
150export function collectWrappedTerminalLinkLine(
151 bufferLineNumber: number,
152 getLine: (bufferLineIndex: number) => TerminalBufferLineLike | null | undefined,
153): WrappedTerminalLinkLine | null {
154 const anchorLine = getLine(bufferLineNumber - 1);
155 if (!anchorLine) return null;
156​
157 let startBufferLineNumber = bufferLineNumber;
158 let startLine = anchorLine;
159​
160 while (startBufferLineNumber > 1 && startLine.isWrapped) {
161 const previousLine = getLine(startBufferLineNumber - 2);
162 if (!previousLine) return null;
163 startBufferLineNumber -= 1;
164 startLine = previousLine;
165 }
166​
167 const segments: WrappedTerminalLinkLineSegment[] = [];
168 let nextStartIndex = 0;
169 let currentBufferLineNumber = startBufferLineNumber;
170​
171 while (true) {
172 const currentLine = getLine(currentBufferLineNumber - 1);
173 if (!currentLine) break;
174​
175 const nextLine = getLine(currentBufferLineNumber);
176 const hasWrappedContinuation = nextLine?.isWrapped === true;
177 const text = currentLine.translateToString(!hasWrappedContinuation);
178​
179 segments.push({
180 bufferLineNumber: currentBufferLineNumber,
181 text,
182 startIndex: nextStartIndex,
183 endIndex: nextStartIndex + text.length,
184 });
185 nextStartIndex += text.length;
186​
187 if (!hasWrappedContinuation) break;
188 currentBufferLineNumber += 1;
189 }
190​
191 return {
192 text: segments.map((segment) => segment.text).join(""),
193 segments,
194 };
196​
197export function isTerminalLinkActivation(
198 event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
199 platform = typeof navigator === "undefined" ? "" : navigator.platform,
200): boolean {
201 if (platform.length === 0) return false;
202 return isMacPlatform(platform)
203 ? event.metaKey && !event.ctrlKey
204 : event.ctrlKey && !event.metaKey;
206​
207export function resolvePathLinkTarget(rawPath: string, cwd: string): string {
208 const position = splitFilePathPosition(rawPath);
209 const { path } = position;
210​
211 let resolvedPath = path;
212 if (path.startsWith("~/")) {
213 const home = inferHomeFromCwd(cwd);
214 if (home) {
215 const separator: "/" | "\\" = isWindowsPathStyle(home) ? "\\" : "/";
216 resolvedPath = joinPath(home, path.slice(2), separator);
217 }
218 } else if (!isAbsolutePath(path)) {
219 const separator: "/" | "\\" = isWindowsPathStyle(cwd) ? "\\" : "/";
220 resolvedPath = joinPath(cwd, path, separator);
221 }
222​
223 return formatFilePathPosition({ ...position, path: resolvedPath });