pi-model-manager 0.4.8 → 0.4.10

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,590 +0,0 @@
1
- // tui/persistent-menu.ts
2
- //
3
- // 共享的"光标记忆"菜单组件,用 ctx.ui.custom 实现。
4
- // 调用方在循环间持有 cursor: { index } 引用,菜单进出时光标位置不丢。
5
- //
6
- // 设计:列表页保留 KISS 的键盘模型,同时支持摘要、列头、详情区、底部快捷键。
7
- // 表单页另有 Ctrl+S 保存;列表页可注册单键快捷操作,并用 / 做轻量过滤。
8
-
9
- import type { ExtensionCommandContext, Theme } from "@earendil-works/pi-coding-agent";
10
- import { CURSOR_MARKER, Key, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
11
- import { t } from "../i18n.ts";
12
-
13
- export interface MenuRow {
14
- id: string;
15
- label: string;
16
- // [喵喵喵]: label 是按列宽截断后的表格文本,长 ID 的后半段不在其中;
17
- // 需要按真实标识搜索的调用方必须显式提供未截断的 searchText。
18
- searchText?: string;
19
- // [喵喵喵]: 可调整性属于行自身;开关切换会让字段集变化(如开 Thinking 后才出现 Adaptive 行),
20
- // 放在外部集合里就会在行重建后与实际行脱节,新出现的开关行按 ←→ 没反应。
21
- adjustable?: boolean;
22
- }
23
-
24
- // 底部快捷键提示;key 与说明分开才能分别着色,并在窄终端按项折行而不是被截掉。
25
- export interface MenuHint {
26
- key: string;
27
- label: string;
28
- }
29
-
30
- export interface PersistentMenuOptions {
31
- summaryLines?: readonly string[];
32
- // [喵喵喵]: 就地切换字段时,摘要也可能依赖草稿状态;渲染时取值才能同步刷新。
33
- getSummaryLines?: () => readonly string[];
34
- // [喵喵喵]: 渲染回调拿到 theme 才能给列与详情上语义色;theme 只存在于 custom 回调作用域。
35
- tableHeader?: string | ((width: number, theme: Theme) => string);
36
- formatRow?: (row: MenuRow, width: number, theme: Theme) => string;
37
- getDetailLines?: (selectedRow: MenuRow | undefined, theme: Theme) => readonly string[];
38
- hints?: readonly MenuHint[];
39
- emptyLabel?: string;
40
- visibleRows?: number;
41
- searchable?: boolean;
42
- }
43
-
44
- export interface PersistentFormMenuOptions extends PersistentMenuOptions {
45
- // 就地切换该字段并返回重建后的行;返回 undefined 则忽略本次按键。
46
- onAdjust?: (id: string, direction: HorizontalDirection) => MenuRow[] | undefined;
47
- }
48
-
49
- export type MenuAction =
50
- | { type: "pick"; id: string }
51
- | { type: "cancel" };
52
-
53
- export type HorizontalDirection = "left" | "right";
54
- // 横向切换已改为组件内处理,不再作为外部动作返回。
55
- export type FormMenuAction = MenuAction | { type: "save" };
56
-
57
- export type ShortcutMenuAction<TShortcut extends string = string> = MenuAction | { type: "shortcut"; shortcut: TShortcut };
58
-
59
- export interface MenuShortcut<TShortcut extends string = string> {
60
- input: string;
61
- shortcut: TShortcut;
62
- }
63
-
64
- export interface MenuCursor {
65
- index: number;
66
- }
67
-
68
- function clampIndex(index: number, length: number): number {
69
- if (length <= 0) return 0;
70
- return Math.min(Math.max(0, index), length - 1);
71
- }
72
-
73
- function padToVisibleWidth(text: string, targetWidth: number): string {
74
- const pad = Math.max(0, targetWidth - visibleWidth(text));
75
- return text + " ".repeat(pad);
76
- }
77
-
78
- export function padLabel(label: string, columns: number): string {
79
- return padToVisibleWidth(label, columns);
80
- }
81
-
82
- // [喵喵喵]: 可左右键切换的行值两侧加滑块标记,让能力直接可见
83
- export function markAdjustableValue(value: string): string {
84
- return `◀ ${value} ▶`;
85
- }
86
-
87
- function getSearchText(row: MenuRow): string {
88
- return (row.searchText ?? `${row.id}\n${row.label}`).toLocaleLowerCase();
89
- }
90
-
91
- const HINT_GAP = " ";
92
-
93
- // 按项贪心排版:单行装不下就换行,保证窄终端下 Esc 等尾部提示不会被 truncate 丢失。
94
- function layoutHintLines(hints: readonly MenuHint[], theme: Theme, width: number): string[] {
95
- const lines: string[] = [];
96
- let currentText = "";
97
- let currentWidth = 0;
98
- for (const hint of hints) {
99
- const hintWidth = visibleWidth(`${hint.key} ${hint.label}`);
100
- const styled = `${theme.fg("accent", hint.key)} ${theme.fg("dim", hint.label)}`;
101
- if (!currentText) {
102
- currentText = styled;
103
- currentWidth = hintWidth;
104
- continue;
105
- }
106
- if (currentWidth + HINT_GAP.length + hintWidth > width) {
107
- lines.push(currentText);
108
- currentText = styled;
109
- currentWidth = hintWidth;
110
- continue;
111
- }
112
- currentText += `${HINT_GAP}${styled}`;
113
- currentWidth += HINT_GAP.length + hintWidth;
114
- }
115
- if (currentText) lines.push(currentText);
116
- return lines;
117
- }
118
-
119
- // 滚动条字符在不同终端的宽度属于 ambiguous,因此固定预留 2 列,宁可多一个空格也不让行溢出。
120
- const SCROLLBAR_WIDTH = 2;
121
-
122
- // pi 在菜单下方还要渲染输入框与状态行,不预留就会把菜单底部的快捷键提示顶出屏幕。
123
- const RESERVED_TERMINAL_ROWS = 3;
124
- // 小于这个高度就无法同时容纳边框、标题、提示和列表,此时宁可溢出也不再继续压缩。
125
- const MIN_MENU_ROWS = 8;
126
- const MIN_LIST_ROWS = 1;
127
-
128
- function getScrollbarGlyph(rowOffset: number, viewportRows: number, windowStart: number, totalRows: number): string {
129
- const thumbRows = Math.max(1, Math.round((viewportRows * viewportRows) / totalRows));
130
- const maxWindowStart = Math.max(1, totalRows - viewportRows);
131
- const thumbStart = Math.round((windowStart / maxWindowStart) * (viewportRows - thumbRows));
132
- return rowOffset >= thumbStart && rowOffset < thumbStart + thumbRows ? "█" : "│";
133
- }
134
-
135
- function filterRows(rows: MenuRow[], query: string): MenuRow[] {
136
- const needle = query.trim().toLocaleLowerCase();
137
- if (!needle) return rows;
138
- return rows.filter((row) => getSearchText(row).includes(needle));
139
- }
140
-
141
- function isSearchTextInput(data: string): boolean {
142
- return data.length > 0 && !data.startsWith("\x1b") && !/[\u0000-\u001f\u007f]/.test(data);
143
- }
144
-
145
- function fitSearchQueryAroundCursor(query: string, cursor: number, cursorGlyph: string, maxWidth: number): string {
146
- if (maxWidth <= 0) return "";
147
- const characters = Array.from(query);
148
- const cursorWidth = visibleWidth(cursorGlyph);
149
- const textBudget = Math.max(0, maxWidth - cursorWidth);
150
- let beforeCursor = "";
151
- let beforeWidth = 0;
152
- for (let index = Math.min(cursor, characters.length) - 1; index >= 0; index -= 1) {
153
- const character = characters[index]!;
154
- const characterWidth = visibleWidth(character);
155
- if (beforeWidth + characterWidth > textBudget) break;
156
- beforeCursor = character + beforeCursor;
157
- beforeWidth += characterWidth;
158
- }
159
- let afterCursor = "";
160
- let afterWidth = 0;
161
- for (let index = Math.min(cursor, characters.length); index < characters.length; index += 1) {
162
- const character = characters[index]!;
163
- const characterWidth = visibleWidth(character);
164
- if (beforeWidth + afterWidth + characterWidth > textBudget) break;
165
- afterCursor += character;
166
- afterWidth += characterWidth;
167
- }
168
- return `${beforeCursor}${cursorGlyph}${afterCursor}`;
169
- }
170
-
171
- function createPersistentMenu<TAction extends MenuAction | FormMenuAction | ShortcutMenuAction>(
172
- ctx: ExtensionCommandContext,
173
- title: string,
174
- help: string,
175
- rows: MenuRow[],
176
- cursor: MenuCursor,
177
- createSaveAction: (() => TAction) | undefined,
178
- shortcuts: MenuShortcut[],
179
- // [喵喵喵]: 横向切换是纯本地状态变更,必须在组件内完成。早期实现用 done() 结束组件再由
180
- // 调用方重开,每按一次方向键都会销毁重建整个 TUI,在终端上表现为闪烁。
181
- // 回调就地改写草稿并返回新行,返回 undefined 表示本次不可调整。
182
- onAdjust: ((id: string, direction: HorizontalDirection) => MenuRow[] | undefined) | undefined = undefined,
183
- options: PersistentMenuOptions = {},
184
- ): Promise<TAction> {
185
- cursor.index = clampIndex(cursor.index, rows.length);
186
- return ctx.ui.custom<TAction>((tui, theme, _keybindings, done) => {
187
- let selectedIndex = clampIndex(cursor.index, rows.length);
188
- let searchActive = false;
189
- let searchQuery = "";
190
- let searchCursor = 0;
191
- let focused = false;
192
- const configuredVisibleRows = options.visibleRows ?? 18;
193
- // [喵喵喵]: 真实可见行数要减去本帧的标题/摘要/详情/提示,每帧在 render 里重算,
194
- // 翻页也必须用同一个值,否则矮终端上 PgUp/PgDn 会跳过看不见的行。
195
- let viewportRows = configuredVisibleRows;
196
- const searchable = options.searchable ?? false;
197
-
198
- // onAdjust 会整批替换行数据,因此不能直接闭包参数 rows。
199
- let currentRows = rows;
200
- const getActiveRows = (): MenuRow[] => searchable ? filterRows(currentRows, searchQuery) : currentRows;
201
-
202
- const syncCursor = (activeRows: MenuRow[]): void => {
203
- const row = activeRows[selectedIndex];
204
- if (row) {
205
- cursor.index = currentRows.indexOf(row);
206
- } else {
207
- // [喵喵喵]: 过滤为空时重置光标为 -1,防止外层快捷键取到陈旧索引误操作隐藏条目
208
- cursor.index = -1;
209
- }
210
- };
211
-
212
- const requestRender = (): void => {
213
- const activeRows = getActiveRows();
214
- selectedIndex = clampIndex(selectedIndex, activeRows.length);
215
- syncCursor(activeRows);
216
- tui.requestRender();
217
- };
218
-
219
- const clearSearch = (): boolean => {
220
- if (!searchable || (!searchActive && !searchQuery)) return false;
221
- searchActive = false;
222
- searchQuery = "";
223
- searchCursor = 0;
224
- selectedIndex = clampIndex(cursor.index, currentRows.length);
225
- requestRender();
226
- return true;
227
- };
228
-
229
- const replaceSearchQuery = (nextQuery: string, nextCursor: number): void => {
230
- const selectedRow = getActiveRows()[selectedIndex];
231
- searchQuery = nextQuery;
232
- searchCursor = clampIndex(nextCursor, Array.from(searchQuery).length + 1);
233
- const nextRows = getActiveRows();
234
- const retainedIndex = selectedRow ? nextRows.indexOf(selectedRow) : -1;
235
- selectedIndex = retainedIndex >= 0 ? retainedIndex : 0;
236
- requestRender();
237
- };
238
-
239
- const pickSelected = (): void => {
240
- const activeRows = getActiveRows();
241
- const row = activeRows[selectedIndex];
242
- if (!row) return;
243
- syncCursor(activeRows);
244
- done({ type: "pick", id: row.id } as TAction);
245
- };
246
-
247
- const moveSelection = (nextIndex: number): void => {
248
- selectedIndex = nextIndex;
249
- requestRender();
250
- };
251
- // 输入态显示带光标的搜索行;Tab 退出后仍需告知用户过滤仍生效。
252
- const renderQueryLine = (width: number): string => {
253
- if (!searchActive) {
254
- return truncateToWidth(`${theme.fg("dim", t("过滤:"))}${searchQuery}`, width, "");
255
- }
256
- const cursorGlyph = focused ? `${CURSOR_MARKER}${theme.fg("accent", "▌")}` : "";
257
- const searchPrefix = theme.fg("accent", t("搜索:"));
258
- const queryWidth = Math.max(0, width - visibleWidth(searchPrefix));
259
- const queryDisplay = searchQuery
260
- ? fitSearchQueryAroundCursor(searchQuery, searchCursor, cursorGlyph, queryWidth)
261
- : `${cursorGlyph}${theme.fg("dim", t("<输入关键词>"))}`;
262
- return truncateToWidth(`${searchPrefix}${queryDisplay}`, width, "");
263
- };
264
-
265
- const getHints = (): MenuHint[] => {
266
- const hints: MenuHint[] = [...(options.hints ?? [])];
267
- if (!searchable) return hints;
268
- if (searchActive) hints.push({ key: "Tab", label: t("保留过滤") }, { key: "Esc", label: t("清空搜索") });
269
- else if (searchQuery) hints.push({ key: "Tab", label: t("继续输入") }, { key: "Esc", label: t("清空过滤") });
270
- else hints.push({ key: "/", label: t("搜索") });
271
- return hints;
272
- };
273
-
274
- // 终端高度未知(如测试环境)时不限制总行数,交由调用方配置的 visibleRows 控制。
275
- const getRowBudget = (): number => {
276
- const terminalRows = tui.terminal?.rows ?? 0;
277
- if (terminalRows <= 0) return Number.POSITIVE_INFINITY;
278
- return Math.max(MIN_MENU_ROWS, terminalRows - RESERVED_TERMINAL_ROWS);
279
- };
280
-
281
- return {
282
- get focused(): boolean {
283
- return focused;
284
- },
285
- set focused(value: boolean) {
286
- focused = value;
287
- },
288
- invalidate(): void {},
289
- handleInput(data: string): void {
290
- if (createSaveAction && matchesKey(data, Key.ctrl("s"))) {
291
- syncCursor(getActiveRows());
292
- done(createSaveAction());
293
- return;
294
- }
295
- const horizontalDirection: HorizontalDirection | undefined = matchesKey(data, Key.left)
296
- ? "left"
297
- : matchesKey(data, Key.right)
298
- ? "right"
299
- : undefined;
300
- if (horizontalDirection && onAdjust) {
301
- const row = getActiveRows()[selectedIndex];
302
- if (row?.adjustable) {
303
- syncCursor(getActiveRows());
304
- const nextRows = onAdjust(row.id, horizontalDirection);
305
- if (nextRows) {
306
- currentRows = nextRows;
307
- requestRender();
308
- }
309
- }
310
- return;
311
- }
312
-
313
- if (searchable && (matchesKey(data, Key.escape) || matchesKey(data, Key.ctrl("c")))) {
314
- if (clearSearch()) return;
315
- done({ type: "cancel" } as TAction);
316
- return;
317
- }
318
-
319
- if (searchable && searchActive) {
320
- const queryCharacters = Array.from(searchQuery);
321
- if (matchesKey(data, Key.backspace)) {
322
- if (searchCursor > 0) {
323
- queryCharacters.splice(searchCursor - 1, 1);
324
- replaceSearchQuery(queryCharacters.join(""), searchCursor - 1);
325
- }
326
- return;
327
- }
328
- if (matchesKey(data, Key.delete)) {
329
- if (searchCursor < queryCharacters.length) {
330
- queryCharacters.splice(searchCursor, 1);
331
- replaceSearchQuery(queryCharacters.join(""), searchCursor);
332
- }
333
- return;
334
- }
335
- if (matchesKey(data, Key.left)) {
336
- searchCursor = Math.max(0, searchCursor - 1);
337
- requestRender();
338
- return;
339
- }
340
- if (matchesKey(data, Key.right)) {
341
- searchCursor = Math.min(queryCharacters.length, searchCursor + 1);
342
- requestRender();
343
- return;
344
- }
345
- if (matchesKey(data, Key.home)) {
346
- searchCursor = 0;
347
- requestRender();
348
- return;
349
- }
350
- if (matchesKey(data, Key.end)) {
351
- searchCursor = queryCharacters.length;
352
- requestRender();
353
- return;
354
- }
355
- // [喵喵喵]: Tab 只退出输入态并保留过滤结果,让用户搜到目标后还能按单字母快捷键;Esc 才清空。
356
- if (matchesKey(data, Key.tab)) {
357
- searchActive = false;
358
- requestRender();
359
- return;
360
- }
361
- if (matchesKey(data, Key.enter)) {
362
- pickSelected();
363
- return;
364
- }
365
- if (isSearchTextInput(data)) {
366
- queryCharacters.splice(searchCursor, 0, ...Array.from(data));
367
- replaceSearchQuery(queryCharacters.join(""), searchCursor + Array.from(data).length);
368
- return;
369
- }
370
- }
371
-
372
- // [喵喵喵]: 提示里快捷键显示为大写,因此 Shift 组合也必须命中同一个动作。
373
- const shortcut = shortcuts.find((candidate) => candidate.input.toLowerCase() === data.toLowerCase());
374
- if (shortcut) {
375
- syncCursor(getActiveRows());
376
- done({ type: "shortcut", shortcut: shortcut.shortcut } as TAction);
377
- return;
378
- }
379
- if (searchable && searchQuery && matchesKey(data, Key.tab)) {
380
- searchActive = true;
381
- searchCursor = Array.from(searchQuery).length;
382
- requestRender();
383
- return;
384
- }
385
- if (searchable && data === "/") {
386
- searchActive = true;
387
- searchCursor = Array.from(searchQuery).length;
388
- requestRender();
389
- return;
390
- }
391
-
392
- if (matchesKey(data, Key.escape) || matchesKey(data, Key.ctrl("c"))) {
393
- done({ type: "cancel" } as TAction);
394
- return;
395
- }
396
- if (matchesKey(data, Key.enter)) {
397
- pickSelected();
398
- return;
399
- }
400
-
401
- const activeRows = getActiveRows();
402
- if (matchesKey(data, Key.up)) {
403
- moveSelection(Math.max(0, selectedIndex - 1));
404
- return;
405
- }
406
- if (matchesKey(data, Key.down)) {
407
- moveSelection(Math.min(activeRows.length - 1, selectedIndex + 1));
408
- return;
409
- }
410
- if (matchesKey(data, Key.pageUp)) {
411
- moveSelection(Math.max(0, selectedIndex - viewportRows));
412
- return;
413
- }
414
- if (matchesKey(data, Key.pageDown)) {
415
- moveSelection(Math.min(activeRows.length - 1, selectedIndex + viewportRows));
416
- return;
417
- }
418
- if (matchesKey(data, Key.home)) {
419
- moveSelection(0);
420
- return;
421
- }
422
- if (matchesKey(data, Key.end)) {
423
- moveSelection(activeRows.length - 1);
424
- return;
425
- }
426
- },
427
- render(width: number): string[] {
428
- const activeRows = getActiveRows();
429
- selectedIndex = clampIndex(selectedIndex, activeRows.length);
430
- syncCursor(activeRows);
431
-
432
- const border = theme.fg("borderMuted", "─".repeat(Math.max(0, width)));
433
- const hintLines = layoutHintLines(getHints(), theme, width);
434
- const summarySource = options.getSummaryLines?.()
435
- ?? options.summaryLines
436
- ?? (help ? help.split("\n") : []);
437
- const summaryLines = summarySource
438
- .map((line) => truncateToWidth(theme.fg("dim", line), width));
439
- const searchLine = searchable && (searchActive || searchQuery) ? renderQueryLine(width) : undefined;
440
- const tableHeaderText = typeof options.tableHeader === "function"
441
- ? options.tableHeader(width, theme)
442
- : options.tableHeader;
443
- // [喵喵喵]: 详情文本由调用方按语义着色,这里只负责裁剪,避免外层样式与内层 reset 互相打断。
444
- const detailLines = (options.getDetailLines?.(activeRows[selectedIndex], theme) ?? [])
445
- .map((line) => truncateToWidth(line, width));
446
-
447
- // [喵喵喵]: 矮终端下按优先级降级:上下边框、标题、快捷键提示和最小列表必须保留,
448
- // 剩余空间才依次发给搜索行、表头、摘要、详情;否则总行数超过终端高度时底部提示会被裁掉。
449
- const budget = getRowBudget();
450
- const essentialRows = 2 + 1 + 1 + (hintLines.length > 0 ? hintLines.length + 1 : 0);
451
- // [喵喵喵]: 列表装不下时底部会多一行位置提示,先按最坏情况预留;
452
- // 放到算出 viewportRows 之后再扣,在列表已压到最小时就无处可扣了。
453
- const scrollHintRows = activeRows.length > MIN_LIST_ROWS ? 1 : 0;
454
- let spare = budget - essentialRows - MIN_LIST_ROWS - scrollHintRows;
455
-
456
- const showSearchLine = searchLine !== undefined && spare >= 1;
457
- if (showSearchLine) spare -= 1;
458
- const showTableHeader = Boolean(tableHeaderText) && spare >= 1;
459
- if (showTableHeader) spare -= 1;
460
- const showSummary = summaryLines.length > 0 && spare >= summaryLines.length;
461
- if (showSummary) spare -= summaryLines.length;
462
- const detailBlockRows = detailLines.length > 0 ? detailLines.length + 2 : 0;
463
- const showDetail = detailBlockRows > 0 && spare >= detailBlockRows;
464
- if (showDetail) spare -= detailBlockRows;
465
-
466
- viewportRows = Math.min(configuredVisibleRows, MIN_LIST_ROWS + Math.max(0, spare));
467
-
468
- const headLines: string[] = [
469
- border,
470
- truncateToWidth(theme.fg("accent", theme.bold(title)), width),
471
- ];
472
- if (showSummary) headLines.push(...summaryLines);
473
- if (showSearchLine) headLines.push(searchLine!);
474
- headLines.push("");
475
- if (showTableHeader) headLines.push(truncateToWidth(theme.fg("dim", tableHeaderText!), width));
476
-
477
- const tailLines: string[] = [];
478
- if (showDetail) tailLines.push("", border, ...detailLines);
479
- if (hintLines.length > 0) tailLines.push("", ...hintLines.map((line) => truncateToWidth(line, width)));
480
- tailLines.push(border);
481
-
482
- const windowStart = Math.max(
483
- 0,
484
- Math.min(selectedIndex - Math.floor(viewportRows / 2), Math.max(0, activeRows.length - viewportRows)),
485
- );
486
- const shownRows = activeRows.slice(windowStart, windowStart + viewportRows);
487
- const scrolling = activeRows.length > viewportRows;
488
- const contentWidth = Math.max(0, scrolling ? width - SCROLLBAR_WIDTH : width);
489
-
490
- const bodyLines: string[] = [];
491
- if (shownRows.length === 0) {
492
- const emptyLabel = searchQuery ? t("无匹配项:{query}", { query: searchQuery }) : options.emptyLabel ?? t("暂无条目");
493
- bodyLines.push(truncateToWidth(theme.fg("dim", ` ${emptyLabel}`), width));
494
- } else {
495
- for (let offset = 0; offset < shownRows.length; offset += 1) {
496
- const row = shownRows[offset]!;
497
- const selected = windowStart + offset === selectedIndex;
498
- const prefix = selected ? "❯ " : " ";
499
- const rowLabel = options.formatRow?.(row, Math.max(0, contentWidth - visibleWidth(prefix)), theme) ?? row.label;
500
- const rowText = truncateToWidth(`${prefix}${rowLabel}`, contentWidth);
501
- // [喵喵喵]: 选中行用背景色而不是整行前景色,列内的语义色才不会被抹平。
502
- const styledRow = selected ? theme.bg("selectedBg", padToVisibleWidth(rowText, contentWidth)) : rowText;
503
- bodyLines.push(scrolling
504
- ? `${styledRow} ${theme.fg("borderMuted", getScrollbarGlyph(offset, viewportRows, windowStart, activeRows.length))}`
505
- : styledRow);
506
- }
507
- if (scrolling) {
508
- const position = `${windowStart + 1}-${windowStart + shownRows.length} / ${activeRows.length}`;
509
- bodyLines.push(theme.fg("dim", padToVisibleWidth("", Math.max(0, contentWidth - visibleWidth(position))) + position));
510
- }
511
- }
512
-
513
- return [...headLines, ...bodyLines, ...tailLines].map((line) => truncateToWidth(line, width));
514
- },
515
- };
516
- });
517
- }
518
-
519
- // 内部基础菜单:对外只暴露 showOptionPicker / showPersistentFormMenu / showPersistentShortcutMenu 三个语义入口。
520
- async function showPersistentMenu(
521
- ctx: ExtensionCommandContext,
522
- title: string,
523
- help: string,
524
- rows: MenuRow[],
525
- cursor: MenuCursor,
526
- options: PersistentMenuOptions = {},
527
- ): Promise<MenuAction> {
528
- return createPersistentMenu<MenuAction>(ctx, title, help, rows, cursor, undefined, [], undefined, options);
529
- }
530
- // 单选弹窗:两个编辑器的所有枚举字段都走这里,避免同一表单里出现两种选择器外观。
531
- export async function showOptionPicker<TChoice extends { id: string; label: string }>(
532
- ctx: ExtensionCommandContext,
533
- title: string,
534
- choices: readonly TChoice[],
535
- currentId: string,
536
- ): Promise<TChoice | undefined> {
537
- const cursor: MenuCursor = { index: Math.max(0, choices.findIndex((choice) => choice.id === currentId)) };
538
- const action = await showPersistentMenu(
539
- ctx,
540
- title,
541
- "",
542
- choices.map((choice) => ({
543
- id: choice.id,
544
- label: choice.id === currentId ? `${choice.label} ${t("● 当前")}` : choice.label,
545
- })),
546
- cursor,
547
- {
548
- hints: [
549
- { key: "↑↓", label: t("移动") },
550
- { key: "Enter", label: t("选择") },
551
- { key: "Esc", label: t("返回") },
552
- ],
553
- },
554
- );
555
- if (action.type === "cancel") return undefined;
556
- return choices.find((choice) => choice.id === action.id);
557
- }
558
-
559
- export async function showPersistentFormMenu(
560
- ctx: ExtensionCommandContext,
561
- title: string,
562
- help: string,
563
- rows: MenuRow[],
564
- cursor: MenuCursor,
565
- options: PersistentFormMenuOptions = {},
566
- ): Promise<FormMenuAction> {
567
- return createPersistentMenu<FormMenuAction>(
568
- ctx,
569
- title,
570
- help,
571
- rows,
572
- cursor,
573
- () => ({ type: "save" }),
574
- [],
575
- options.onAdjust,
576
- options,
577
- );
578
- }
579
-
580
- export async function showPersistentShortcutMenu<TShortcut extends string>(
581
- ctx: ExtensionCommandContext,
582
- title: string,
583
- help: string,
584
- rows: MenuRow[],
585
- cursor: MenuCursor,
586
- shortcuts: MenuShortcut<TShortcut>[],
587
- options: PersistentMenuOptions = {},
588
- ): Promise<ShortcutMenuAction<TShortcut>> {
589
- return createPersistentMenu<ShortcutMenuAction<TShortcut>>(ctx, title, help, rows, cursor, undefined, shortcuts, undefined, { searchable: true, ...options });
590
- }