@lune_99/pi-core-theme 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,175 +1,9 @@
1
- import {
2
- copyToClipboard,
3
- type ExtensionContext,
4
- type Theme,
5
- } from "@earendil-works/pi-coding-agent";
6
- import {
7
- Key,
8
- matchesKey,
9
- sliceByColumn,
10
- truncateToWidth,
11
- visibleWidth,
12
- type Component,
13
- type TuiMouseEvent,
14
- } from "@earendil-works/pi-tui";
15
- import { sanitizeToolResultText } from "../utils/tool-result-sanitize.ts";
1
+ import { copyToClipboard, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { Key, matchesKey, truncateToWidth, type TuiMouseEvent } from "@earendil-works/pi-tui";
3
+ import { TextPanel } from "./text-panel.ts";
16
4
 
17
5
  export type OutputContent = () => string | Promise<string>;
18
6
 
19
- /** A plain-text viewport preserves every output line and column without laying out hidden content. */
20
- class OutputPanel implements Component {
21
- private readonly lines: string[];
22
- private readonly maxColumns: number;
23
- private top = 0;
24
- private left = 0;
25
- private width = 1;
26
- private pageSize = 1;
27
- private cached?: {
28
- width: number;
29
- height: number;
30
- top: number;
31
- left: number;
32
- colors: unknown;
33
- lines: string[];
34
- };
35
- private readonly title: string;
36
- private readonly content: string;
37
- private readonly theme: () => Theme;
38
- private readonly rows: () => number;
39
- private readonly repaint: () => void;
40
- private readonly close: () => void;
41
- private readonly notify: ExtensionContext["ui"]["notify"];
42
-
43
- constructor(
44
- title: string,
45
- content: string,
46
- theme: () => Theme,
47
- rows: () => number,
48
- repaint: () => void,
49
- close: () => void,
50
- notify: ExtensionContext["ui"]["notify"],
51
- ) {
52
- this.title = title;
53
- this.content = sanitizeToolResultText(content).replace(/\t/g, " ");
54
- this.lines = this.content.split("\n");
55
- this.maxColumns = this.lines.reduce(
56
- (maximum, line) => Math.max(maximum, visibleWidth(line)),
57
- 0,
58
- );
59
- this.theme = theme;
60
- this.rows = rows;
61
- this.repaint = repaint;
62
- this.close = close;
63
- this.notify = notify;
64
- }
65
- invalidate() {
66
- this.cached = undefined;
67
- }
68
- private scroll(vertical: number, horizontal = 0) {
69
- this.top = Math.max(0, Math.min(this.lines.length - this.pageSize, this.top + vertical));
70
- this.left = Math.max(
71
- 0,
72
- Math.min(this.maxColumns - Math.max(1, this.width - 4), this.left + horizontal),
73
- );
74
- this.repaint();
75
- }
76
- private copy() {
77
- void copyToClipboard(this.content).then(
78
- () => this.notify("Copied full output", "info"),
79
- (error) => this.notify(String(error), "error"),
80
- );
81
- }
82
- handleInput(data: string) {
83
- if (matchesKey(data, Key.escape)) this.close();
84
- else if (matchesKey(data, Key.down)) this.scroll(1);
85
- else if (matchesKey(data, Key.up)) this.scroll(-1);
86
- else if (matchesKey(data, Key.pageDown)) this.scroll(this.pageSize);
87
- else if (matchesKey(data, Key.pageUp)) this.scroll(-this.pageSize);
88
- else if (matchesKey(data, Key.home)) this.scroll(-this.lines.length, -this.maxColumns);
89
- else if (matchesKey(data, Key.end)) this.scroll(this.lines.length);
90
- else if (matchesKey(data, Key.right))
91
- this.scroll(0, Math.max(1, Math.floor(this.width / 2)));
92
- else if (matchesKey(data, Key.left))
93
- this.scroll(0, -Math.max(1, Math.floor(this.width / 2)));
94
- else if (data === "c" || matchesKey(data, Key.ctrl("c"))) this.copy();
95
- }
96
- handleMouse(event: TuiMouseEvent) {
97
- if (event.type === "wheel") {
98
- this.scroll(event.wheelDelta ?? 0);
99
- return { handled: true };
100
- }
101
- return event.type === "move" || (event.type === "click" && event.button === "left")
102
- ? { handled: true }
103
- : undefined;
104
- }
105
- render(width: number): string[] {
106
- this.width = width;
107
- const height = Math.max(7, Math.min(40, this.rows() - 4));
108
- this.pageSize = height - 6;
109
- const inner = Math.max(0, width - 4);
110
- this.top = Math.min(this.top, Math.max(0, this.lines.length - this.pageSize));
111
- this.left = Math.min(this.left, Math.max(0, this.maxColumns - inner));
112
- const theme = this.theme();
113
- const cached = this.cached;
114
- if (
115
- cached &&
116
- cached.width === width &&
117
- cached.height === height &&
118
- cached.top === this.top &&
119
- cached.left === this.left &&
120
- cached.colors === theme.colors
121
- )
122
- return cached.lines;
123
- const border = (text: string) => theme.fg("borderMuted", text);
124
- const pad = (text: string, available = inner) => {
125
- const clipped = truncateToWidth(text, Math.max(0, available), "");
126
- return clipped + " ".repeat(Math.max(0, available - visibleWidth(clipped)));
127
- };
128
- const row = (text: string) => border("│ ") + pad(text) + border(" │");
129
- const title = truncateToWidth(theme.bold(theme.fg("accent", this.title)), inner, "…");
130
- const status = truncateToWidth(
131
- theme.fg(
132
- "dim",
133
- `${this.top + 1}–${Math.min(this.lines.length, this.top + this.pageSize)} / ${this.lines.length} lines · column ${this.left + 1}`,
134
- ),
135
- Math.max(0, inner - visibleWidth(title) - 1),
136
- "…",
137
- );
138
- const separator = border(`├${"─".repeat(Math.max(0, width - 2))}┤`);
139
- const body = this.lines
140
- .slice(this.top, this.top + this.pageSize)
141
- .map((line) => row(theme.fg("toolOutput", sliceByColumn(line, this.left, inner))));
142
- while (body.length < this.pageSize) body.push(row(""));
143
- const lines = [
144
- border(`╭${"─".repeat(Math.max(0, width - 2))}╮`),
145
- row(
146
- title +
147
- " ".repeat(Math.max(0, inner - visibleWidth(title) - visibleWidth(status))) +
148
- status,
149
- ),
150
- separator,
151
- ...body,
152
- separator,
153
- row(
154
- theme.fg(
155
- "dim",
156
- "Full output · ↑↓ / wheel · PgUp/PgDn · ←→ columns · Home/End · c to copy · Esc to close",
157
- ),
158
- ),
159
- border(`╰${"─".repeat(Math.max(0, width - 2))}╯`),
160
- ].map((line) => truncateToWidth(line, width, ""));
161
- this.cached = {
162
- width,
163
- height,
164
- top: this.top,
165
- left: this.left,
166
- colors: theme.colors,
167
- lines,
168
- };
169
- return lines;
170
- }
171
- }
172
-
173
7
  /** The active renderer session owns one output overlay and closes it during reload or deactivation. */
174
8
  export function createOutputBrowser(context: Pick<ExtensionContext, "ui">) {
175
9
  let disposed = false;
@@ -190,20 +24,21 @@ export function createOutputBrowser(context: Pick<ExtensionContext, "ui">) {
190
24
  done();
191
25
  };
192
26
  entry.close = finish;
193
- let panel: OutputPanel | undefined;
27
+ let panel: TextPanel | undefined;
194
28
  void Promise.resolve()
195
29
  .then(content)
196
30
  .then((text) => {
197
31
  if (closed || disposed) return;
198
- panel = new OutputPanel(
32
+ panel = new TextPanel({
199
33
  title,
200
- text,
201
- () => context.ui.theme,
202
- () => tui.terminal.rows,
203
- () => tui.requestRender(),
204
- finish,
205
- (message, level) => context.ui.notify(message, level),
206
- );
34
+ items: [{ label: "Full output", content: text }],
35
+ theme: () => context.ui.theme,
36
+ rows: () => tui.terminal.rows,
37
+ repaint: () => tui.requestRender(),
38
+ close: finish,
39
+ copy: copyToClipboard,
40
+ notify: (message, level) => context.ui.notify(message, level),
41
+ });
207
42
  tui.requestRender();
208
43
  })
209
44
  .catch((error) => {
@@ -0,0 +1,357 @@
1
+ import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ Key,
4
+ matchesKey,
5
+ truncateToWidth,
6
+ visibleWidth,
7
+ wrapTextWithAnsi,
8
+ type Component,
9
+ type TuiMouseEvent,
10
+ } from "@earendil-works/pi-tui";
11
+ import { sanitizeToolResultText } from "../utils/tool-result-sanitize.ts";
12
+
13
+ export interface TextPanelItem {
14
+ label: string;
15
+ content: string;
16
+ detail?: string;
17
+ badge?: string;
18
+ color?: Parameters<Theme["fg"]>[0];
19
+ render?: (content: string, width: number, theme: Theme) => string[];
20
+ }
21
+
22
+ export interface TextPanelOptions {
23
+ title: string;
24
+ items: readonly TextPanelItem[];
25
+ subtitle?: string;
26
+ header?: (width: number, theme: Theme) => readonly string[];
27
+ navigationTitle?: string;
28
+ maxHeight?: number;
29
+ theme: () => Theme;
30
+ rows: () => number;
31
+ repaint: () => void;
32
+ close: () => void;
33
+ copy: (content: string) => Promise<void>;
34
+ notify: ExtensionContext["ui"]["notify"];
35
+ }
36
+
37
+ interface Document {
38
+ content: string;
39
+ lines: string[];
40
+ wrapped?: { width: number; colors: unknown; rows: string[] };
41
+ }
42
+
43
+ /** Output and context share wrapped content; categorized panels route input by pane. */
44
+ export class TextPanel implements Component {
45
+ private readonly options: TextPanelOptions;
46
+ private readonly documents = new Map<number, Document>();
47
+ private selected = 0;
48
+ private top = 0;
49
+ private pageSize = 1;
50
+ private bodyWidth = 1;
51
+ private bodyStart = 3;
52
+ private sidebar = 0;
53
+ private navigationTop = 0;
54
+ private laidOut = false;
55
+ private cached?: {
56
+ width: number;
57
+ height: number;
58
+ selected: number;
59
+ top: number;
60
+ colors: unknown;
61
+ lines: string[];
62
+ };
63
+
64
+ constructor(options: TextPanelOptions) {
65
+ this.options = options;
66
+ }
67
+
68
+ private document(): Document {
69
+ let document = this.documents.get(this.selected);
70
+ if (!document) {
71
+ const content = sanitizeToolResultText(
72
+ this.options.items[this.selected]!.content,
73
+ ).replace(/\t/g, " ");
74
+ const lines = content.split("\n");
75
+ document = { content, lines };
76
+ this.documents.set(this.selected, document);
77
+ }
78
+ return document;
79
+ }
80
+
81
+ invalidate() {
82
+ this.cached = undefined;
83
+ }
84
+
85
+ private contentRows(): string[] {
86
+ const document = this.document();
87
+ const item = this.options.items[this.selected]!;
88
+ const theme = this.options.theme();
89
+ // As in Shell Inspector, wrapping is cached by pane width rather than repeated per wheel tick.
90
+ if (
91
+ document.wrapped?.width !== this.bodyWidth ||
92
+ (item.render && document.wrapped.colors !== theme.colors)
93
+ ) {
94
+ document.wrapped = {
95
+ width: this.bodyWidth,
96
+ colors: theme.colors,
97
+ rows: item.render
98
+ ? item.render(document.content, this.bodyWidth, theme)
99
+ : document.lines.flatMap((line) => wrapTextWithAnsi(line, this.bodyWidth)),
100
+ };
101
+ }
102
+ return document.wrapped.rows;
103
+ }
104
+
105
+ private select(index: number) {
106
+ const next = Math.max(0, Math.min(this.options.items.length - 1, index));
107
+ if (next === this.selected) return;
108
+ this.selected = next;
109
+ this.top = 0;
110
+ this.options.repaint();
111
+ }
112
+
113
+ private scroll(vertical: number) {
114
+ this.top = Math.max(
115
+ 0,
116
+ Math.min(this.contentRows().length - this.pageSize, this.top + vertical),
117
+ );
118
+ this.options.repaint();
119
+ }
120
+
121
+ private copy() {
122
+ void this.options.copy(this.document().content).then(
123
+ () =>
124
+ this.options.notify(
125
+ this.options.items.length > 1 ? "Copied category" : "Copied full output",
126
+ "info",
127
+ ),
128
+ (error) => this.options.notify(String(error), "error"),
129
+ );
130
+ }
131
+
132
+ handleInput(data: string) {
133
+ const categories = this.options.items.length > 1;
134
+ if (matchesKey(data, Key.escape)) this.options.close();
135
+ else if (matchesKey(data, Key.shift("down"))) this.scroll(1);
136
+ else if (matchesKey(data, Key.shift("up"))) this.scroll(-1);
137
+ else if (matchesKey(data, Key.down)) {
138
+ if (categories) this.select(this.selected + 1);
139
+ else this.scroll(1);
140
+ } else if (matchesKey(data, Key.up)) {
141
+ if (categories) this.select(this.selected - 1);
142
+ else this.scroll(-1);
143
+ } else if (matchesKey(data, Key.pageDown)) this.scroll(this.pageSize);
144
+ else if (matchesKey(data, Key.pageUp)) this.scroll(-this.pageSize);
145
+ else if (matchesKey(data, Key.home)) this.scroll(-this.contentRows().length);
146
+ else if (matchesKey(data, Key.end)) this.scroll(this.contentRows().length);
147
+ else if (data === "c" || matchesKey(data, Key.ctrl("c"))) this.copy();
148
+ }
149
+
150
+ handleMouse(event: TuiMouseEvent) {
151
+ if (!this.laidOut) return undefined;
152
+ if (event.type === "wheel") {
153
+ if (this.sidebar && event.x < this.sidebar + 4)
154
+ this.select(this.selected + (event.wheelDelta ?? 0));
155
+ else this.scroll(event.wheelDelta ?? 0);
156
+ // Claim both panes so wheel events never reach the transcript behind the overlay.
157
+ return { handled: true };
158
+ }
159
+ if (
160
+ event.type === "press" &&
161
+ event.button === "left" &&
162
+ this.sidebar &&
163
+ event.x >= 2 &&
164
+ event.x < 2 + this.sidebar &&
165
+ event.y >= this.bodyStart &&
166
+ event.y < this.bodyStart + this.pageSize
167
+ ) {
168
+ const index = this.navigationTop + event.y - this.bodyStart;
169
+ if (index < this.options.items.length) {
170
+ this.select(index);
171
+ return { handled: true };
172
+ }
173
+ }
174
+ // Leave output presses and drags to Pi's native text selection, like Shell Inspector.
175
+ return undefined;
176
+ }
177
+
178
+ render(width: number): string[] {
179
+ const { items, subtitle, navigationTitle } = this.options;
180
+ const categories = items.length > 1;
181
+ const inner = Math.max(0, width - 4);
182
+ const theme = this.options.theme();
183
+ const customHeader = this.options.header?.(inner, theme);
184
+ this.sidebar = categories ? Math.min(28, Math.floor(inner * 0.3)) : 0;
185
+ const extraHeaders = customHeader ? customHeader.length - 1 : Number(!!subtitle);
186
+ const paneHeader = !!navigationTitle && !!this.sidebar;
187
+ const height = Math.max(
188
+ 7 + extraHeaders + Number(paneHeader),
189
+ Math.min(this.options.maxHeight ?? 40, this.options.rows() - 4),
190
+ );
191
+ this.bodyStart = 3 + extraHeaders + Number(paneHeader);
192
+ this.pageSize = Math.max(1, height - 6 - extraHeaders - Number(paneHeader));
193
+ const rightWidth = Math.max(1, inner - (this.sidebar ? this.sidebar + 2 : 0));
194
+ this.bodyWidth = Math.max(1, rightWidth - (paneHeader ? 2 : 0));
195
+ this.navigationTop = Math.max(
196
+ 0,
197
+ Math.min(this.selected - Math.floor(this.pageSize / 2), items.length - this.pageSize),
198
+ );
199
+ this.laidOut = true;
200
+ const contentRows = this.contentRows();
201
+ this.top = Math.min(this.top, Math.max(0, contentRows.length - this.pageSize));
202
+ const cached = this.cached;
203
+ if (
204
+ cached &&
205
+ cached.width === width &&
206
+ cached.height === height &&
207
+ cached.selected === this.selected &&
208
+ cached.top === this.top &&
209
+ cached.colors === theme.colors
210
+ )
211
+ return cached.lines;
212
+ const border = (text: string) => theme.fg("borderMuted", text);
213
+ const pad = (text: string, available: number) => {
214
+ const clipped = truncateToWidth(text, available, "");
215
+ return clipped + " ".repeat(Math.max(0, available - visibleWidth(clipped)));
216
+ };
217
+ const row = (text: string) => border("│ ") + pad(text, inner) + border(" │");
218
+ const item = items[this.selected]!;
219
+ const title = truncateToWidth(
220
+ theme.bold(theme.fg("accent", this.options.title)),
221
+ inner,
222
+ "…",
223
+ );
224
+ const status = truncateToWidth(
225
+ theme.fg(
226
+ "dim",
227
+ `${this.document().lines.length} lines · ${this.top + 1}–${Math.min(contentRows.length, this.top + this.pageSize)} / ${contentRows.length} rows`,
228
+ ),
229
+ Math.max(0, inner - visibleWidth(title) - 1),
230
+ "…",
231
+ );
232
+ const separator = (joint: "┬" | "┴") =>
233
+ this.sidebar
234
+ ? border(
235
+ `├${"─".repeat(this.sidebar + 1)}${joint}${"─".repeat(Math.max(0, width - this.sidebar - 4))}┤`,
236
+ )
237
+ : border(`├${"─".repeat(Math.max(0, width - 2))}┤`);
238
+ const headers: string[] = [];
239
+ if (subtitle)
240
+ headers.push(
241
+ row(theme.fg("muted", `${subtitle}${item.detail ? ` · ${item.detail}` : ""}`)),
242
+ );
243
+ const pair = (left: string, right: string, available: number) => {
244
+ const end = truncateToWidth(
245
+ right,
246
+ Math.max(0, available - visibleWidth(left) - 1),
247
+ "…",
248
+ );
249
+ return pad(left, Math.max(0, available - visibleWidth(end))) + end;
250
+ };
251
+ const contentHeading = paneHeader
252
+ ? row(
253
+ pad(theme.fg("dim", navigationTitle!), this.sidebar) +
254
+ border("│ ") +
255
+ pair(
256
+ theme.bold(theme.fg("text", item.label)),
257
+ theme.fg(
258
+ "dim",
259
+ `${item.badge ? `${item.badge} est. · ` : ""}${this.top + 1}–${Math.min(contentRows.length, this.top + this.pageSize)} / ${contentRows.length}`,
260
+ ),
261
+ rightWidth,
262
+ ),
263
+ )
264
+ : undefined;
265
+ const thumbSize = Math.max(
266
+ 1,
267
+ Math.floor((this.pageSize * this.pageSize) / contentRows.length),
268
+ );
269
+ const thumbTop =
270
+ contentRows.length > this.pageSize
271
+ ? Math.round(
272
+ (this.top / (contentRows.length - this.pageSize)) *
273
+ (this.pageSize - thumbSize),
274
+ )
275
+ : 0;
276
+ const body = Array.from({ length: this.pageSize }, (_, index) => {
277
+ let text = theme.fg("toolOutput", contentRows[this.top + index] ?? "");
278
+ if (paneHeader) {
279
+ const scrollable = contentRows.length > this.pageSize;
280
+ const thumb = index >= thumbTop && index < thumbTop + thumbSize;
281
+ text =
282
+ pad(text, this.bodyWidth) +
283
+ " " +
284
+ (scrollable
285
+ ? theme.fg(thumb ? "scrollbarThumb" : "scrollbarTrack", thumb ? "┃" : "│")
286
+ : " ");
287
+ }
288
+ if (!this.sidebar) return row(text);
289
+ const navigationIndex = this.navigationTop + index;
290
+ const entry = items[navigationIndex];
291
+ const selected = navigationIndex === this.selected;
292
+ const color = entry?.color ?? "accent";
293
+ const prefix = theme.fg(selected ? "accent" : "dim", selected ? "› " : " ");
294
+ const mark = entry?.color ? theme.fg(color, "● ") : "";
295
+ const label = entry
296
+ ? prefix +
297
+ mark +
298
+ (selected
299
+ ? theme.bold(theme.fg("text", entry.label))
300
+ : theme.fg("muted", entry.label))
301
+ : "";
302
+ let navigation =
303
+ entry?.badge && this.sidebar >= 22
304
+ ? pair(label, theme.fg(selected ? color : "dim", entry.badge), this.sidebar)
305
+ : pad(label, this.sidebar);
306
+ if (selected && navigationTitle) navigation = theme.bg("selectedBg", navigation);
307
+ return row(navigation + border("│ ") + text);
308
+ });
309
+ const hints = categories
310
+ ? inner >= 90
311
+ ? "↑↓ categories · wheel per pane · Shift+↑↓ / PgUp/PgDn scroll · Home/End · c copy · Esc close"
312
+ : inner >= 60
313
+ ? "↑↓ categories · wheel/⇧↑↓ scroll · PgUp/Dn · c copy · Esc close"
314
+ : inner >= 48
315
+ ? "↑↓ categories · wheel scroll · c copy · Esc close"
316
+ : inner >= 36
317
+ ? "↑↓ select · wheel scroll · Esc close"
318
+ : "↑↓ · c · Esc"
319
+ : inner >= 74
320
+ ? "Full output · ↑↓ / wheel · PgUp/PgDn · Home/End · c to copy · Esc to close"
321
+ : inner >= 40
322
+ ? "↑↓/wheel · PgUp/Dn · c copy · Esc close"
323
+ : inner >= 28
324
+ ? "↑↓/wheel · c copy · Esc close"
325
+ : "↑↓ · c · Esc";
326
+ const lines = [
327
+ border(`╭${"─".repeat(Math.max(0, width - 2))}╮`),
328
+ ...(customHeader
329
+ ? customHeader.map((line) => row(line))
330
+ : [
331
+ row(
332
+ title +
333
+ " ".repeat(
334
+ Math.max(0, inner - visibleWidth(title) - visibleWidth(status)),
335
+ ) +
336
+ status,
337
+ ),
338
+ ...headers,
339
+ ]),
340
+ separator("┬"),
341
+ ...(contentHeading ? [contentHeading] : []),
342
+ ...body,
343
+ separator("┴"),
344
+ row(theme.fg("dim", hints)),
345
+ border(`╰${"─".repeat(Math.max(0, width - 2))}╯`),
346
+ ].map((line) => truncateToWidth(line, width, ""));
347
+ this.cached = {
348
+ width,
349
+ height,
350
+ selected: this.selected,
351
+ top: this.top,
352
+ colors: theme.colors,
353
+ lines,
354
+ };
355
+ return lines;
356
+ }
357
+ }
@@ -0,0 +1,5 @@
1
+ export function formatTokens(tokens: number): string {
2
+ if (tokens < 1000) return String(tokens);
3
+ if (tokens < 100000) return `${(tokens / 1000).toFixed(1)}k`;
4
+ return `${Math.round(tokens / 1000)}k`;
5
+ }
@@ -0,0 +1,67 @@
1
+ import { existsSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { isAbsolute, join, resolve } from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { getCapabilities, hyperlink } from "@earendil-works/pi-tui";
6
+
7
+ const urlPattern = /https?:\/\/[^\s<>"'`|,。;:!?、」』】()【】《》『』「」]+/g;
8
+ // File URLs cannot carry an editor location, so `:line[:column]` and `#anchor` suffixes are dropped.
9
+ const location = /(?::\d+(?:-\d+)?){1,2}$|#.*$/;
10
+
11
+ function trimUrl(value: string) {
12
+ let url = value.replace(/[.,;:!?}"']+$/, "");
13
+ for (const [open, close] of [
14
+ ["(", ")"],
15
+ ["[", "]"],
16
+ ] as const) {
17
+ while (url.endsWith(close) && url.split(close).length > url.split(open).length)
18
+ url = url.slice(0, -1);
19
+ }
20
+ return url;
21
+ }
22
+
23
+ /** Without OSC 8 support Pi prints a link's target beside its text, so paths stay unlinked. */
24
+ export function hyperlinksEnabled(): boolean {
25
+ return getCapabilities().hyperlinks;
26
+ }
27
+
28
+ /** A file URL for an explicit local reference to an existing file or directory. */
29
+ export function fileHref(path: string, cwd: string): string | undefined {
30
+ const target = path.replace(location, "");
31
+ // URI schemes, scp targets and network shares must not become local existence checks.
32
+ if (
33
+ !/\w/.test(target) ||
34
+ /^[\\/]{2}/.test(path) ||
35
+ /^[^/\\]*@[^/\\]*:/.test(path) ||
36
+ (/^[^/\\]*:/.test(target) && !isAbsolute(target)) ||
37
+ /[\u0000-\u001f\u007f]/.test(path)
38
+ )
39
+ return undefined;
40
+ const absolute = target.startsWith("~/")
41
+ ? join(homedir(), target.slice(1))
42
+ : resolve(cwd, target);
43
+ return existsSync(absolute) ? pathToFileURL(absolute).href : undefined;
44
+ }
45
+
46
+ const wholeUrl = new RegExp(`^${urlPattern.source}$`);
47
+
48
+ /** The target for text that is exactly one complete HTTP(S) URL, with no trailing punctuation. */
49
+ export function webHref(value: string): string | undefined {
50
+ return wholeUrl.test(value) && trimUrl(value) === value ? value : undefined;
51
+ }
52
+
53
+ /** Replace HTTP(S) URLs in plain text, leaving trailing punctuation outside the replacement. */
54
+ export function replaceLinks(
55
+ value: string,
56
+ render: (text: string, href: string) => string,
57
+ ): string {
58
+ return value.replace(urlPattern, (match) => {
59
+ const text = trimUrl(match);
60
+ return text ? render(text, text) + match.slice(text.length) : match;
61
+ });
62
+ }
63
+
64
+ /** Plain text gains OSC 8 links only for HTTP(S) URLs. */
65
+ export function linkText(value: string): string {
66
+ return hyperlinksEnabled() ? replaceLinks(value, hyperlink) : value;
67
+ }