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

terminal-links.ts

219 lines6.2 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​
39function trimClosingDelimiters(value: string): string {
40 let output = value.replace(TRAILING_PUNCTUATION_PATTERN, "");
41 if (output.length === 0) return output;
42​
43 const trimUnbalanced = (open: string, close: string) => {
44 while (output.endsWith(close)) {
45 const opens = output.split(open).length - 1;
46 const closes = output.split(close).length - 1;
47 if (opens >= closes) return;
48 output = output.slice(0, -1);
49 }
50 };
51​
52 trimUnbalanced("(", ")");
53 trimUnbalanced("[", "]");
54 trimUnbalanced("{", "}");
55 return output;
57​
58function overlaps(a: { start: number; end: number }, b: { start: number; end: number }): boolean {
59 return a.start < b.end && b.start < a.end;
61​
62function collectMatches(
63 line: string,
64 kind: TerminalLinkKind,
65 pattern: RegExp,
66 existing: TerminalLinkMatch[],
67): TerminalLinkMatch[] {
68 const matches: TerminalLinkMatch[] = [];
69 pattern.lastIndex = 0;
70​
71 for (const rawMatch of line.matchAll(pattern)) {
72 const raw = rawMatch[0];
73 const start = rawMatch.index ?? -1;
74 if (start < 0 || raw.length === 0) continue;
75​
76 const trimmed = trimClosingDelimiters(raw);
77 if (trimmed.length === 0) continue;
78 if (kind === "path" && isTerminalUrl(trimmed)) continue;
79​
80 const candidate: TerminalLinkMatch = {
81 kind,
82 text: trimmed,
83 start,
84 end: start + trimmed.length,
85 };
86​
87 const collides = [...existing, ...matches].some((other) => overlaps(candidate, other));
88 if (collides) continue;
89​
90 matches.push(candidate);
91 }
92​
93 return matches;
95​
96function isWindowsAbsolutePath(value: string): boolean {
97 return /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("\\\\");
99​
100export function isAbsolutePath(value: string): boolean {
101 return value.startsWith("/") || isWindowsAbsolutePath(value);
103​
104function isWindowsPathStyle(value: string): boolean {
105 return isWindowsAbsolutePath(value) || /[A-Za-z]:\\/.test(value);
107​
108function joinPath(base: string, next: string, separator: "/" | "\\"): string {
109 const cleanBase = base.replace(/[\\/]+$/, "");
110 if (separator === "\\") {
111 return `${cleanBase}\\${next.replaceAll("/", "\\")}`;
112 }
113 return `${cleanBase}/${next.replace(/^\/+/, "")}`;
115​
116function inferHomeFromCwd(cwd: string): string | undefined {
117 const posixUser = cwd.match(/^\/Users\/([^/]+)/);
118 if (posixUser?.[1]) {
119 return `/Users/${posixUser[1]}`;
120 }
121​
122 const posixHome = cwd.match(/^\/home\/([^/]+)/);
123 if (posixHome?.[1]) {
124 return `/home/${posixHome[1]}`;
125 }
126​
127 const windowsUser = cwd.match(/^([A-Za-z]:\\Users\\[^\\]+)/);
128 if (windowsUser?.[1]) {
129 return windowsUser[1];
130 }
131​
132 return undefined;
134​
135export function extractTerminalLinks(line: string): TerminalLinkMatch[] {
136 const urlMatches = collectMatches(line, "url", URL_PATTERN, []);
137 const pathMatches = collectMatches(line, "path", FILE_PATH_PATTERN, urlMatches);
138 return [...urlMatches, ...pathMatches].toSorted((a, b) => a.start - b.start);
140​
141export function isTerminalUrl(value: string): boolean {
142 return /^https?:\/\//iu.test(value);
144​
145export function collectWrappedTerminalLinkLine(
146 bufferLineNumber: number,
147 getLine: (bufferLineIndex: number) => TerminalBufferLineLike | null | undefined,
148): WrappedTerminalLinkLine | null {
149 const anchorLine = getLine(bufferLineNumber - 1);
150 if (!anchorLine) return null;
151​
152 let startBufferLineNumber = bufferLineNumber;
153 let startLine = anchorLine;
154​
155 while (startBufferLineNumber > 1 && startLine.isWrapped) {
156 const previousLine = getLine(startBufferLineNumber - 2);
157 if (!previousLine) return null;
158 startBufferLineNumber -= 1;
159 startLine = previousLine;
160 }
161​
162 const segments: WrappedTerminalLinkLineSegment[] = [];
163 let nextStartIndex = 0;
164 let currentBufferLineNumber = startBufferLineNumber;
165​
166 while (true) {
167 const currentLine = getLine(currentBufferLineNumber - 1);
168 if (!currentLine) break;
169​
170 const nextLine = getLine(currentBufferLineNumber);
171 const hasWrappedContinuation = nextLine?.isWrapped === true;
172 const text = currentLine.translateToString(!hasWrappedContinuation);
173​
174 segments.push({
175 bufferLineNumber: currentBufferLineNumber,
176 text,
177 startIndex: nextStartIndex,
178 endIndex: nextStartIndex + text.length,
179 });
180 nextStartIndex += text.length;
181​
182 if (!hasWrappedContinuation) break;
183 currentBufferLineNumber += 1;
184 }
185​
186 return {
187 text: segments.map((segment) => segment.text).join(""),
188 segments,
189 };
191​
192export function isTerminalLinkActivation(
193 event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
194 platform = typeof navigator === "undefined" ? "" : navigator.platform,
195): boolean {
196 if (platform.length === 0) return false;
197 return isMacPlatform(platform)
198 ? event.metaKey && !event.ctrlKey
199 : event.ctrlKey && !event.metaKey;
201​
202export function resolvePathLinkTarget(rawPath: string, cwd: string): string {
203 const position = splitFilePathPosition(rawPath);
204 const { path } = position;
205​
206 let resolvedPath = path;
207 if (path.startsWith("~/")) {
208 const home = inferHomeFromCwd(cwd);
209 if (home) {
210 const separator: "/" | "\\" = isWindowsPathStyle(home) ? "\\" : "/";
211 resolvedPath = joinPath(home, path.slice(2), separator);
212 }
213 } else if (!isAbsolutePath(path)) {
214 const separator: "/" | "\\" = isWindowsPathStyle(cwd) ? "\\" : "/";
215 resolvedPath = joinPath(cwd, path, separator);
216 }
217​
218 return formatFilePathPosition({ ...position, path: resolvedPath });