@narumitw/pi-starship 0.43.0 → 0.45.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.
Files changed (46) hide show
  1. package/README.md +274 -89
  2. package/package.json +2 -2
  3. package/src/command-inspector.ts +470 -0
  4. package/src/command-preview.ts +206 -0
  5. package/src/commands.ts +187 -152
  6. package/src/config.ts +177 -67
  7. package/src/format/style.ts +64 -45
  8. package/src/modules/activity.ts +1 -1
  9. package/src/modules/brand.ts +1 -1
  10. package/src/modules/cache.ts +1 -1
  11. package/src/modules/catalog.ts +65 -4
  12. package/src/modules/context.ts +13 -1
  13. package/src/modules/cost.ts +12 -1
  14. package/src/modules/development.ts +1 -1
  15. package/src/modules/directory.ts +1 -1
  16. package/src/modules/display.ts +14 -0
  17. package/src/modules/execution.ts +12 -1
  18. package/src/modules/extension-status.ts +7 -98
  19. package/src/modules/fill.ts +1 -1
  20. package/src/modules/git/branch.ts +3 -37
  21. package/src/modules/git/commit.ts +1 -1
  22. package/src/modules/git/metrics.ts +8 -2
  23. package/src/modules/git/runtime.ts +5 -2
  24. package/src/modules/git/state.ts +1 -1
  25. package/src/modules/git/status.ts +1 -1
  26. package/src/modules/git/worktree.ts +1 -1
  27. package/src/modules/github-pr.ts +24 -0
  28. package/src/modules/index.ts +15 -6
  29. package/src/modules/inspection.ts +138 -0
  30. package/src/modules/model.ts +1 -1
  31. package/src/modules/provider.ts +1 -1
  32. package/src/modules/render.ts +23 -19
  33. package/src/modules/thinking.ts +1 -1
  34. package/src/modules/time.ts +1 -1
  35. package/src/modules/tokens.ts +1 -1
  36. package/src/modules/turn.ts +1 -1
  37. package/src/modules/types.ts +32 -5
  38. package/src/pi-starship.ts +149 -27
  39. package/src/runtime/command.ts +46 -8
  40. package/src/runtime/execution.ts +15 -3
  41. package/src/runtime/github-pr.ts +332 -0
  42. package/src/runtime/helpers.ts +1 -0
  43. package/src/runtime/refresh-controller.ts +30 -8
  44. package/src/runtime/types.ts +4 -0
  45. package/src/runtime/workspace.ts +27 -10
  46. package/src/installed-packages.ts +0 -84
@@ -0,0 +1,470 @@
1
+ import { stripVTControlCharacters } from "node:util";
2
+ import type { ExtensionCommandContext, KeybindingsManager } from "@earendil-works/pi-coding-agent";
3
+ import {
4
+ type Component,
5
+ type Focusable,
6
+ Input,
7
+ Key,
8
+ matchesKey,
9
+ truncateToWidth,
10
+ wrapTextWithAnsi,
11
+ } from "@earendil-works/pi-tui";
12
+ import type { ModuleInspection, StatuslineInspection } from "./modules/inspection.js";
13
+
14
+ const RESERVED_HOST_ROWS = 3;
15
+
16
+ export type InspectorResult = { kind: "back" } | { kind: "close" };
17
+
18
+ type DisposableComponent = Component & Focusable & { dispose(): void };
19
+
20
+ export function showFooterExplanation(
21
+ ctx: ExtensionCommandContext,
22
+ inspection: StatuslineInspection | undefined,
23
+ signal?: AbortSignal,
24
+ ): Promise<InspectorResult | undefined> {
25
+ if (signal?.aborted) return Promise.resolve({ kind: "close" });
26
+ return ctx.ui.custom<InspectorResult | undefined>((tui, theme, keybindings, done) => {
27
+ let scrollOffset = 0;
28
+ let lastMaximumScroll = 0;
29
+ let lastViewportSize = 1;
30
+ let disposed = false;
31
+ let settled = false;
32
+ let deferredAbort: ReturnType<typeof setImmediate> | undefined;
33
+ const finish = (result: InspectorResult) => {
34
+ if (disposed || settled) return;
35
+ settled = true;
36
+ done(result);
37
+ };
38
+ const closeForAbort = () => finish({ kind: "close" });
39
+ signal?.addEventListener("abort", closeForAbort, { once: true });
40
+ if (signal?.aborted) deferredAbort = setImmediate(closeForAbort);
41
+
42
+ return {
43
+ focused: false,
44
+ render(width: number): string[] {
45
+ const safeWidth = Math.max(1, width);
46
+ const availableRows = componentRows(tui.terminal.rows);
47
+ const content = explanationLines(inspection, safeWidth);
48
+ const layout = detailLayout(availableRows, content.length);
49
+ lastViewportSize = layout.contentRows;
50
+ lastMaximumScroll = Math.max(0, content.length - layout.contentRows);
51
+ scrollOffset = clamp(scrollOffset, 0, lastMaximumScroll);
52
+ const lines = [
53
+ ...(layout.titleRows ? [theme.fg("accent", theme.bold("Explain footer"))] : []),
54
+ ...content.slice(scrollOffset, scrollOffset + layout.contentRows),
55
+ ...(layout.positionRows
56
+ ? [theme.fg("dim", positionText(scrollOffset, layout.contentRows, content.length))]
57
+ : []),
58
+ ...(layout.hintRows ? [theme.fg("dim", detailHint(keybindings, "back"))] : []),
59
+ ];
60
+ return boundedLines(lines, safeWidth, availableRows);
61
+ },
62
+ invalidate() {},
63
+ handleInput(data: string) {
64
+ if (disposed || settled) return;
65
+ if (matchesKey(data, Key.ctrl("c"))) finish({ kind: "close" });
66
+ else if (keybindings.matches(data, "tui.select.cancel")) finish({ kind: "back" });
67
+ else if (keybindings.matches(data, "tui.select.up")) {
68
+ scrollOffset = clamp(scrollOffset - 1, 0, lastMaximumScroll);
69
+ } else if (keybindings.matches(data, "tui.select.down")) {
70
+ scrollOffset = clamp(scrollOffset + 1, 0, lastMaximumScroll);
71
+ } else if (keybindings.matches(data, "tui.select.pageUp")) {
72
+ scrollOffset = clamp(scrollOffset - lastViewportSize, 0, lastMaximumScroll);
73
+ } else if (keybindings.matches(data, "tui.select.pageDown")) {
74
+ scrollOffset = clamp(scrollOffset + lastViewportSize, 0, lastMaximumScroll);
75
+ } else if (matchesKey(data, Key.home)) scrollOffset = 0;
76
+ else if (matchesKey(data, Key.end)) scrollOffset = lastMaximumScroll;
77
+ tui.requestRender();
78
+ },
79
+ dispose() {
80
+ if (disposed) return;
81
+ disposed = true;
82
+ if (deferredAbort) clearImmediate(deferredAbort);
83
+ deferredAbort = undefined;
84
+ signal?.removeEventListener("abort", closeForAbort);
85
+ },
86
+ };
87
+ });
88
+ }
89
+
90
+ export function showModuleBrowser(
91
+ ctx: ExtensionCommandContext,
92
+ inspection: StatuslineInspection,
93
+ signal?: AbortSignal,
94
+ ): Promise<InspectorResult | undefined> {
95
+ if (signal?.aborted) return Promise.resolve({ kind: "close" });
96
+ return ctx.ui.custom<InspectorResult | undefined>((tui, theme, keybindings, done) => {
97
+ const input = new Input();
98
+ let filtered = [...inspection.modules];
99
+ let selectedIndex = 0;
100
+ let listOffset = 0;
101
+ let detailScrollOffset = 0;
102
+ let lastListRows = 1;
103
+ let searchInputVisible = true;
104
+ let lastDetailRows = 1;
105
+ let lastDetailMaximumScroll = 0;
106
+ let view: "list" | "detail" = "list";
107
+ let focused = false;
108
+ let disposed = false;
109
+ let settled = false;
110
+ let deferredAbort: ReturnType<typeof setImmediate> | undefined;
111
+ const finish = (result: InspectorResult) => {
112
+ if (disposed || settled) return;
113
+ settled = true;
114
+ done(result);
115
+ };
116
+ const closeForAbort = () => finish({ kind: "close" });
117
+ signal?.addEventListener("abort", closeForAbort, { once: true });
118
+ if (signal?.aborted) deferredAbort = setImmediate(closeForAbort);
119
+ const selected = () => filtered[selectedIndex];
120
+ const syncFocus = () => {
121
+ input.focused = focused && view === "list";
122
+ };
123
+ const select = (index: number) => {
124
+ if (filtered.length === 0) return;
125
+ selectedIndex = (index + filtered.length) % filtered.length;
126
+ };
127
+ const applySearch = () => {
128
+ const sanitized = safeSearchText(input.getValue());
129
+ if (sanitized !== input.getValue()) input.setValue(sanitized);
130
+ filtered = filterModules(inspection.modules, sanitized);
131
+ selectedIndex = 0;
132
+ listOffset = 0;
133
+ };
134
+
135
+ const component: DisposableComponent = {
136
+ get focused() {
137
+ return focused;
138
+ },
139
+ set focused(value: boolean) {
140
+ focused = value;
141
+ syncFocus();
142
+ },
143
+ render(width: number): string[] {
144
+ const safeWidth = Math.max(1, width);
145
+ const availableRows = componentRows(tui.terminal.rows);
146
+ if (view === "detail") {
147
+ const module = selected();
148
+ const content = moduleDetailLines(module, safeWidth);
149
+ const layout = detailLayout(availableRows, content.length);
150
+ lastDetailRows = layout.contentRows;
151
+ lastDetailMaximumScroll = Math.max(0, content.length - layout.contentRows);
152
+ detailScrollOffset = clamp(detailScrollOffset, 0, lastDetailMaximumScroll);
153
+ const lines = [
154
+ ...(layout.titleRows ? [theme.fg("accent", theme.bold(module?.name ?? "Module"))] : []),
155
+ ...content.slice(detailScrollOffset, detailScrollOffset + layout.contentRows),
156
+ ...(layout.positionRows
157
+ ? [
158
+ theme.fg(
159
+ "dim",
160
+ positionText(detailScrollOffset, layout.contentRows, content.length),
161
+ ),
162
+ ]
163
+ : []),
164
+ ...(layout.hintRows ? [theme.fg("dim", detailHint(keybindings, "back"))] : []),
165
+ ];
166
+ return boundedLines(lines, safeWidth, availableRows);
167
+ }
168
+
169
+ const layout = listLayout(availableRows, filtered.length);
170
+ lastListRows = layout.itemRows;
171
+ searchInputVisible = layout.inputRows > 0;
172
+ listOffset = listWindowStart(selectedIndex, filtered.length, layout.itemRows);
173
+ const rows =
174
+ filtered.length === 0
175
+ ? [theme.fg("dim", " No matching modules")]
176
+ : filtered.slice(listOffset, listOffset + layout.itemRows).map((module, index) => {
177
+ const absoluteIndex = listOffset + index;
178
+ const prefix = absoluteIndex === selectedIndex ? "→ " : " ";
179
+ const text = `${prefix}${module.name} [${module.state}]`;
180
+ return theme.fg(absoluteIndex === selectedIndex ? "accent" : "text", text);
181
+ });
182
+ const description = selected()?.description;
183
+ const lines = [
184
+ ...(layout.titleRows ? [theme.fg("accent", theme.bold("Modules · type to search"))] : []),
185
+ ...(layout.inputRows ? input.render(safeWidth) : []),
186
+ ...rows,
187
+ ...(layout.positionRows
188
+ ? [theme.fg("dim", positionText(listOffset, layout.itemRows, filtered.length))]
189
+ : []),
190
+ ...(layout.descriptionRows && description
191
+ ? [theme.fg("muted", safeDisplayText(description))]
192
+ : []),
193
+ ...(layout.hintRows ? [theme.fg("dim", browserHint(keybindings))] : []),
194
+ ];
195
+ return boundedLines(lines, safeWidth, availableRows);
196
+ },
197
+ invalidate() {
198
+ input.invalidate();
199
+ },
200
+ handleInput(data: string) {
201
+ if (disposed || settled) return;
202
+ if (matchesKey(data, Key.ctrl("c"))) {
203
+ finish({ kind: "close" });
204
+ } else if (keybindings.matches(data, "tui.select.cancel")) {
205
+ if (view === "detail") {
206
+ view = "list";
207
+ detailScrollOffset = 0;
208
+ syncFocus();
209
+ } else finish({ kind: "back" });
210
+ } else if (view === "detail") {
211
+ if (keybindings.matches(data, "tui.select.up")) {
212
+ detailScrollOffset = clamp(detailScrollOffset - 1, 0, lastDetailMaximumScroll);
213
+ } else if (keybindings.matches(data, "tui.select.down")) {
214
+ detailScrollOffset = clamp(detailScrollOffset + 1, 0, lastDetailMaximumScroll);
215
+ } else if (keybindings.matches(data, "tui.select.pageUp")) {
216
+ detailScrollOffset = clamp(
217
+ detailScrollOffset - lastDetailRows,
218
+ 0,
219
+ lastDetailMaximumScroll,
220
+ );
221
+ } else if (keybindings.matches(data, "tui.select.pageDown")) {
222
+ detailScrollOffset = clamp(
223
+ detailScrollOffset + lastDetailRows,
224
+ 0,
225
+ lastDetailMaximumScroll,
226
+ );
227
+ } else if (matchesKey(data, Key.home)) detailScrollOffset = 0;
228
+ else if (matchesKey(data, Key.end)) {
229
+ detailScrollOffset = lastDetailMaximumScroll;
230
+ }
231
+ } else if (keybindings.matches(data, "tui.select.up")) {
232
+ select(selectedIndex - 1);
233
+ } else if (keybindings.matches(data, "tui.select.down")) {
234
+ select(selectedIndex + 1);
235
+ } else if (keybindings.matches(data, "tui.select.pageUp")) {
236
+ select(selectedIndex - lastListRows);
237
+ } else if (keybindings.matches(data, "tui.select.pageDown")) {
238
+ select(selectedIndex + lastListRows);
239
+ } else if (matchesKey(data, Key.home)) selectedIndex = 0;
240
+ else if (matchesKey(data, Key.end)) selectedIndex = Math.max(0, filtered.length - 1);
241
+ else if (keybindings.matches(data, "tui.select.confirm")) {
242
+ if (selected()) {
243
+ view = "detail";
244
+ detailScrollOffset = 0;
245
+ syncFocus();
246
+ }
247
+ } else if (searchInputVisible) {
248
+ input.handleInput(data);
249
+ applySearch();
250
+ }
251
+ tui.requestRender();
252
+ },
253
+ dispose() {
254
+ if (disposed) return;
255
+ disposed = true;
256
+ if (deferredAbort) clearImmediate(deferredAbort);
257
+ deferredAbort = undefined;
258
+ signal?.removeEventListener("abort", closeForAbort);
259
+ },
260
+ };
261
+ return component;
262
+ });
263
+ }
264
+
265
+ function explanationLines(inspection: StatuslineInspection | undefined, width: number): string[] {
266
+ if (!inspection) {
267
+ return wrapLines(
268
+ [
269
+ "Footer inspection is unavailable until the TUI footer is ready.",
270
+ "No collection work was started.",
271
+ ],
272
+ width,
273
+ );
274
+ }
275
+ if (inspection.showing.length === 0) {
276
+ return wrapLines(
277
+ [
278
+ "No modules are currently showing.",
279
+ "Open Modules to inspect empty, disabled, or unreachable modules.",
280
+ ],
281
+ width,
282
+ );
283
+ }
284
+ const lines = inspection.showing.flatMap((module, index) => [
285
+ ...(index > 0 ? [""] : []),
286
+ module.name,
287
+ ...previewLines(module.preview),
288
+ module.description,
289
+ ]);
290
+ return wrapLines(lines, width);
291
+ }
292
+
293
+ function moduleDetailLines(module: ModuleInspection | undefined, width: number): string[] {
294
+ if (!module) return ["No matching module."];
295
+ return wrapLines(
296
+ [
297
+ `State: ${module.state}`,
298
+ module.description,
299
+ `Root: ${module.rootReferenced ? "Referenced" : "Not referenced"}`,
300
+ `Reachable: ${module.reachable ? "Yes" : "No"}`,
301
+ ...detailPreviewLines(module.preview),
302
+ `Reason: ${module.reason}`,
303
+ `Variables: ${module.variables.join(", ") || "none"}`,
304
+ `Style fields: ${module.styleFields.join(", ") || "none"}`,
305
+ `Display rules: ${module.displayRules.join(" · ") || "none"}`,
306
+ ],
307
+ width,
308
+ );
309
+ }
310
+
311
+ function previewLines(preview: string): string[] {
312
+ const lines = preview ? preview.split("\n") : ["(no text)"];
313
+ return lines.map((line, index) => `${index === 0 ? "Value: " : " "}${line}`);
314
+ }
315
+
316
+ function detailPreviewLines(preview: string): string[] {
317
+ const lines = preview ? preview.split("\n") : ["(no current preview)"];
318
+ return lines.map((line, index) => `${index === 0 ? "Preview: " : " "}${line}`);
319
+ }
320
+
321
+ function wrapLines(lines: readonly string[], width: number): string[] {
322
+ return lines.flatMap((line) => {
323
+ const safe = safeDisplayText(line);
324
+ return safe ? wrapTextWithAnsi(safe, width) : [""];
325
+ });
326
+ }
327
+
328
+ function filterModules(modules: readonly ModuleInspection[], query: string): ModuleInspection[] {
329
+ const terms = query.toLowerCase().trim().split(/\s+/u).filter(Boolean);
330
+ if (terms.length === 0) return [...modules];
331
+ return modules.filter((module) => {
332
+ const candidate = `${module.name} ${module.description} ${module.state}`.toLowerCase();
333
+ return terms.every((term) => candidate.includes(term));
334
+ });
335
+ }
336
+
337
+ interface DetailLayout {
338
+ titleRows: number;
339
+ contentRows: number;
340
+ positionRows: number;
341
+ hintRows: number;
342
+ }
343
+
344
+ function detailLayout(availableRows: number, contentLength: number): DetailLayout {
345
+ if (availableRows === 1) {
346
+ return { titleRows: 0, contentRows: 1, positionRows: 0, hintRows: 0 };
347
+ }
348
+ const titleRows = availableRows >= 4 ? 1 : 0;
349
+ const hintRows = availableRows >= 3 ? 1 : 0;
350
+ let contentRows = Math.max(1, availableRows - titleRows - hintRows);
351
+ const positionRows = contentLength > contentRows && contentRows >= 2 ? 1 : 0;
352
+ contentRows -= positionRows;
353
+ return { titleRows, contentRows, positionRows, hintRows };
354
+ }
355
+
356
+ interface ListLayout {
357
+ titleRows: number;
358
+ inputRows: number;
359
+ itemRows: number;
360
+ positionRows: number;
361
+ descriptionRows: number;
362
+ hintRows: number;
363
+ }
364
+
365
+ function listLayout(availableRows: number, itemCount: number): ListLayout {
366
+ if (availableRows === 1) {
367
+ return {
368
+ titleRows: 0,
369
+ inputRows: 0,
370
+ itemRows: 1,
371
+ positionRows: 0,
372
+ descriptionRows: 0,
373
+ hintRows: 0,
374
+ };
375
+ }
376
+ const titleRows = availableRows >= 4 ? 1 : 0;
377
+ const inputRows = availableRows >= 3 ? 1 : 0;
378
+ const hintRows = availableRows >= 3 ? 1 : 0;
379
+ const descriptionRows = availableRows >= 7 ? 1 : 0;
380
+ let itemRows = Math.max(1, availableRows - titleRows - inputRows - hintRows - descriptionRows);
381
+ const positionRows = itemCount > itemRows && itemRows >= 2 ? 1 : 0;
382
+ itemRows -= positionRows;
383
+ return { titleRows, inputRows, itemRows, positionRows, descriptionRows, hintRows };
384
+ }
385
+
386
+ function componentRows(rows: number): number {
387
+ const terminalRows = Number.isFinite(rows) ? Math.floor(rows) : 24;
388
+ return Math.max(1, terminalRows - RESERVED_HOST_ROWS);
389
+ }
390
+
391
+ function listWindowStart(selectedIndex: number, itemCount: number, viewportSize: number): number {
392
+ if (itemCount <= viewportSize) return 0;
393
+ return Math.max(0, Math.min(selectedIndex, itemCount - viewportSize));
394
+ }
395
+
396
+ function positionText(offset: number, viewportSize: number, itemCount: number): string {
397
+ if (itemCount === 0) return "0/0";
398
+ return `${offset + 1}-${Math.min(itemCount, offset + viewportSize)}/${itemCount}`;
399
+ }
400
+
401
+ function boundedLines(lines: readonly string[], width: number, rows: number): string[] {
402
+ return lines.slice(0, rows).map((line) => truncateToWidth(line, width, ""));
403
+ }
404
+
405
+ function browserHint(keybindings: Pick<KeybindingsManager, "getKeys">): string {
406
+ const up = bindingText(keybindings, "tui.select.up");
407
+ const down = bindingText(keybindings, "tui.select.down");
408
+ const confirm = bindingText(keybindings, "tui.select.confirm");
409
+ const cancel = bindingText(keybindings, "tui.select.cancel", "ctrl+c");
410
+ return [
411
+ ...(up || down ? [`${[up, down].filter(Boolean).join("/")} navigate`] : []),
412
+ ...(confirm ? [`${confirm} details`] : []),
413
+ ...(cancel ? [`${cancel} back`] : []),
414
+ "ctrl+c close",
415
+ ].join(" • ");
416
+ }
417
+
418
+ function detailHint(
419
+ keybindings: Pick<KeybindingsManager, "getKeys">,
420
+ destination: "back" | "close",
421
+ ): string {
422
+ const up = bindingText(keybindings, "tui.select.up");
423
+ const down = bindingText(keybindings, "tui.select.down");
424
+ const cancel = bindingText(keybindings, "tui.select.cancel", "ctrl+c");
425
+ const pageUp = bindingText(keybindings, "tui.select.pageUp");
426
+ const pageDown = bindingText(keybindings, "tui.select.pageDown");
427
+ return [
428
+ ...(up || down ? [`${[up, down].filter(Boolean).join("/")} scroll`] : []),
429
+ ...(pageUp || pageDown ? [`${[pageUp, pageDown].filter(Boolean).join("/")} page`] : []),
430
+ ...(cancel ? [`${cancel} ${destination}`] : []),
431
+ "ctrl+c close",
432
+ ].join(" • ");
433
+ }
434
+
435
+ function bindingText(
436
+ keybindings: Pick<KeybindingsManager, "getKeys">,
437
+ binding: Parameters<KeybindingsManager["getKeys"]>[0],
438
+ excluded?: string,
439
+ ): string {
440
+ return keybindings
441
+ .getKeys(binding)
442
+ .filter((key) => key !== excluded)
443
+ .map((key) => {
444
+ if (key === "up") return "↑";
445
+ if (key === "down") return "↓";
446
+ if (key === "escape") return "esc";
447
+ if (key === "return") return "enter";
448
+ return safeDisplayText(key);
449
+ })
450
+ .filter(Boolean)
451
+ .join("/");
452
+ }
453
+
454
+ function safeSearchText(value: string): string {
455
+ return Array.from(stripVTControlCharacters(value), (character) => {
456
+ const codePoint = character.codePointAt(0) ?? 0;
457
+ return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? "" : character;
458
+ }).join("");
459
+ }
460
+
461
+ function safeDisplayText(value: string): string {
462
+ return Array.from(stripVTControlCharacters(value), (character) => {
463
+ const codePoint = character.codePointAt(0) ?? 0;
464
+ return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? "" : character;
465
+ }).join("");
466
+ }
467
+
468
+ function clamp(value: number, minimum: number, maximum: number): number {
469
+ return Math.max(minimum, Math.min(value, maximum));
470
+ }
@@ -0,0 +1,206 @@
1
+ import { stripVTControlCharacters } from "node:util";
2
+ import type { ExtensionCommandContext, KeybindingsManager } from "@earendil-works/pi-coding-agent";
3
+ import { Key, matchesKey, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
4
+
5
+ const RESERVED_HOST_ROWS = 3;
6
+
7
+ export interface PreviewMenuItem<Value extends string> {
8
+ value: Value;
9
+ label: string;
10
+ }
11
+
12
+ export type PreviewMenuResult<Value extends string> =
13
+ | { kind: "selected"; value: Value }
14
+ | { kind: "cancelled" }
15
+ | { kind: "closed" };
16
+
17
+ export async function showPreviewActionMenu<Value extends string>(
18
+ ctx: ExtensionCommandContext,
19
+ title: string,
20
+ body: (width: number) => readonly string[],
21
+ items: readonly PreviewMenuItem<Value>[],
22
+ signal?: AbortSignal,
23
+ ): Promise<PreviewMenuResult<Value> | undefined> {
24
+ if (signal?.aborted) return { kind: "closed" };
25
+ return ctx.ui.custom<PreviewMenuResult<Value> | undefined>((tui, theme, keybindings, done) => {
26
+ let selectedIndex = 0;
27
+ let scrollOffset = 0;
28
+ let lastMaximumScroll = 0;
29
+ let lastViewportSize = 1;
30
+ let disposed = false;
31
+ let deferredAbort: ReturnType<typeof setImmediate> | undefined;
32
+ const closeForAbort = () => {
33
+ if (disposed) return;
34
+ if (deferredAbort) clearImmediate(deferredAbort);
35
+ deferredAbort = undefined;
36
+ done({ kind: "closed" });
37
+ };
38
+ signal?.addEventListener("abort", closeForAbort, { once: true });
39
+ if (signal?.aborted) deferredAbort = setImmediate(closeForAbort);
40
+
41
+ const requestRender = () => {
42
+ if (!disposed) tui.requestRender();
43
+ };
44
+ const moveSelection = (delta: number) => {
45
+ if (items.length === 0) return;
46
+ selectedIndex = (selectedIndex + delta + items.length) % items.length;
47
+ requestRender();
48
+ };
49
+ const movePreview = (offset: number) => {
50
+ scrollOffset = Math.max(0, Math.min(offset, lastMaximumScroll));
51
+ requestRender();
52
+ };
53
+
54
+ return {
55
+ render(width: number): string[] {
56
+ const safeWidth = Math.max(1, width);
57
+ const terminalRows = Number.isFinite(tui.terminal.rows)
58
+ ? Math.floor(tui.terminal.rows)
59
+ : 24;
60
+ const availableRows = Math.max(1, terminalRows - RESERVED_HOST_ROWS);
61
+ const bodyLines = body(safeWidth).flatMap((line) =>
62
+ line ? wrapTextWithAnsi(line, safeWidth) : [""],
63
+ );
64
+ const layout = allocateLayout(availableRows, items.length, bodyLines.length);
65
+ lastViewportSize = layout.previewRows;
66
+ lastMaximumScroll = Math.max(0, bodyLines.length - layout.previewRows);
67
+ scrollOffset = Math.max(0, Math.min(scrollOffset, lastMaximumScroll));
68
+ const actionStart = actionWindowStart(selectedIndex, items.length, layout.actionRows);
69
+ const actionLines = items
70
+ .slice(actionStart, actionStart + layout.actionRows)
71
+ .map((item, index) => {
72
+ const absoluteIndex = actionStart + index;
73
+ const prefix = absoluteIndex === selectedIndex ? "→ " : " ";
74
+ return theme.fg(
75
+ absoluteIndex === selectedIndex ? "accent" : "text",
76
+ `${prefix}${safeDisplayText(item.label)}`,
77
+ );
78
+ });
79
+ const position = layout.positionRows
80
+ ? [theme.fg("dim", previewPosition(scrollOffset, layout.previewRows, bodyLines.length))]
81
+ : [];
82
+ const lines = [
83
+ ...(layout.titleRows ? [theme.fg("accent", theme.bold(safeDisplayText(title)))] : []),
84
+ ...bodyLines.slice(scrollOffset, scrollOffset + layout.previewRows),
85
+ ...position,
86
+ ...actionLines,
87
+ ...(layout.hintRows ? [theme.fg("dim", previewHint(keybindings))] : []),
88
+ ];
89
+ return lines.map((line) => truncateToWidth(line, safeWidth, ""));
90
+ },
91
+ invalidate() {},
92
+ handleInput(data: string) {
93
+ if (disposed) return;
94
+ if (matchesKey(data, Key.ctrl("c"))) {
95
+ done({ kind: "closed" });
96
+ } else if (keybindings.matches(data, "tui.select.cancel")) {
97
+ done({ kind: "cancelled" });
98
+ } else if (keybindings.matches(data, "tui.select.up")) {
99
+ moveSelection(-1);
100
+ } else if (keybindings.matches(data, "tui.select.down")) {
101
+ moveSelection(1);
102
+ } else if (keybindings.matches(data, "tui.select.pageUp")) {
103
+ movePreview(scrollOffset - lastViewportSize);
104
+ } else if (keybindings.matches(data, "tui.select.pageDown")) {
105
+ movePreview(scrollOffset + lastViewportSize);
106
+ } else if (matchesKey(data, Key.home)) {
107
+ movePreview(0);
108
+ } else if (matchesKey(data, Key.end)) {
109
+ movePreview(lastMaximumScroll);
110
+ } else if (keybindings.matches(data, "tui.select.confirm")) {
111
+ const item = items[selectedIndex];
112
+ if (item) done({ kind: "selected", value: item.value });
113
+ }
114
+ },
115
+ dispose() {
116
+ if (disposed) return;
117
+ disposed = true;
118
+ if (deferredAbort) clearImmediate(deferredAbort);
119
+ deferredAbort = undefined;
120
+ signal?.removeEventListener("abort", closeForAbort);
121
+ },
122
+ };
123
+ });
124
+ }
125
+
126
+ interface PreviewLayout {
127
+ titleRows: number;
128
+ previewRows: number;
129
+ positionRows: number;
130
+ actionRows: number;
131
+ hintRows: number;
132
+ }
133
+
134
+ function allocateLayout(
135
+ availableRows: number,
136
+ actionCount: number,
137
+ bodyLineCount: number,
138
+ ): PreviewLayout {
139
+ if (availableRows === 1) {
140
+ return { titleRows: 0, previewRows: 0, positionRows: 0, actionRows: 1, hintRows: 0 };
141
+ }
142
+ const titleRows = availableRows >= 3 ? 1 : 0;
143
+ const hintRows = availableRows >= 3 ? 1 : 0;
144
+ const minimumPreviewRows = bodyLineCount > 0 && availableRows >= 4 ? 1 : 0;
145
+ const availableActionRows = Math.max(
146
+ 1,
147
+ availableRows - titleRows - hintRows - minimumPreviewRows,
148
+ );
149
+ const actionRows = Math.min(Math.max(1, actionCount), availableActionRows);
150
+ let previewRows = Math.max(0, availableRows - titleRows - hintRows - actionRows);
151
+ const positionRows = previewRows >= 2 && bodyLineCount > previewRows ? 1 : 0;
152
+ previewRows -= positionRows;
153
+ return { titleRows, previewRows, positionRows, actionRows, hintRows };
154
+ }
155
+
156
+ function actionWindowStart(selectedIndex: number, itemCount: number, viewportSize: number): number {
157
+ if (itemCount <= viewportSize) return 0;
158
+ return Math.max(0, Math.min(selectedIndex, itemCount - viewportSize));
159
+ }
160
+
161
+ function previewPosition(offset: number, viewportSize: number, lineCount: number): string {
162
+ if (lineCount === 0) return "0/0";
163
+ return `${offset + 1}-${Math.min(lineCount, offset + viewportSize)}/${lineCount}`;
164
+ }
165
+
166
+ function previewHint(keybindings: Pick<KeybindingsManager, "getKeys">): string {
167
+ const up = bindingText(keybindings, "tui.select.up");
168
+ const down = bindingText(keybindings, "tui.select.down");
169
+ const confirm = bindingText(keybindings, "tui.select.confirm");
170
+ const cancel = bindingText(keybindings, "tui.select.cancel", "ctrl+c");
171
+ const pageUp = bindingText(keybindings, "tui.select.pageUp");
172
+ const pageDown = bindingText(keybindings, "tui.select.pageDown");
173
+ return [
174
+ ...(up || down ? [`${[up, down].filter(Boolean).join("/")} navigate`] : []),
175
+ ...(confirm ? [`${confirm} select`] : []),
176
+ ...(cancel ? [`${cancel} discard`] : []),
177
+ "ctrl+c close",
178
+ ...(pageUp || pageDown ? [`${[pageUp, pageDown].filter(Boolean).join("/")} preview`] : []),
179
+ ].join(" • ");
180
+ }
181
+
182
+ function bindingText(
183
+ keybindings: Pick<KeybindingsManager, "getKeys">,
184
+ binding: Parameters<KeybindingsManager["getKeys"]>[0],
185
+ excluded?: string,
186
+ ): string {
187
+ return keybindings
188
+ .getKeys(binding)
189
+ .filter((key) => key !== excluded)
190
+ .map((key) => {
191
+ if (key === "up") return "↑";
192
+ if (key === "down") return "↓";
193
+ if (key === "escape") return "esc";
194
+ if (key === "return") return "enter";
195
+ return safeDisplayText(key);
196
+ })
197
+ .join("/");
198
+ }
199
+
200
+ function safeDisplayText(value: string): string {
201
+ return Array.from(stripVTControlCharacters(value), (character) => {
202
+ const codePoint = character.codePointAt(0) ?? 0;
203
+ const control = codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);
204
+ return control ? "" : character;
205
+ }).join("");
206
+ }