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