@0xkahi/pi-qol 1.0.0 → 1.0.1

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,373 +1,134 @@
1
1
  import { modelsAreEqual } from '@earendil-works/pi-ai';
2
2
  import type { KeybindingsManager, Theme } from '@earendil-works/pi-coding-agent';
3
- import { type Component, type Focusable, fuzzyFilter, Input, matchesKey, type TUI, truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
3
+ import type { Component, Focusable, TUI } from '@earendil-works/pi-tui';
4
+ import { ListTab, ModalDialog, type ModalTab } from '../../libs/modal';
4
5
  import { MAX_CONFIG_WARNING_LINES, MAX_VISIBLE_MODELS } from './constants';
5
6
  import { ModelFormatter } from './model-formatter';
6
- import type { DialogOptions, ModelItem, TabIdentity } from './types';
7
-
8
- type DialogTab = {
9
- identity: TabIdentity;
10
- label: string;
11
- items: ModelItem[];
12
- filteredItems: ModelItem[];
13
- selectedIndex: number;
14
- };
7
+ import type { DialogOptions, DialogResult, ModelItem, TabIdentity } from './types';
15
8
 
9
+ /**
10
+ * Model picker dialog: a `ModalDialog` configured with one `ListTab` per
11
+ * section (permanent Favourites, configured groups, Search), a shared filter
12
+ * input, and wrap-around picker navigation driven by the host keybindings.
13
+ */
16
14
  export class ModelSelectDialog implements Component, Focusable {
17
- private readonly searchInput = new Input();
18
- private readonly tabs: DialogTab[];
19
- private activeTabIndex: number;
20
- private _focused = false;
15
+ private readonly dialog: ModalDialog<DialogResult>;
21
16
 
22
17
  constructor(
23
- private readonly tui: TUI,
18
+ tui: TUI,
24
19
  private readonly theme: Theme,
25
- private readonly keybindings: KeybindingsManager,
20
+ keybindings: KeybindingsManager,
26
21
  private readonly options: DialogOptions,
27
22
  ) {
28
- this.tabs = this.createTabs();
29
- const searchTabIndex = this.tabs.findIndex(tab => tab.identity.kind === 'search');
30
- this.activeTabIndex = options.initialSearch && searchTabIndex >= 0 ? searchTabIndex : 0;
31
-
32
- this.searchInput.setValue(options.initialSearch);
33
- this.searchInput.onSubmit = () => this.selectCurrentItem();
34
- this.searchInput.onEscape = () => this.options.onDone(null);
35
- this.applyFilter(options.initialSearch);
36
- this.syncFocus();
37
- }
38
-
39
- get focused(): boolean {
40
- return this._focused;
41
- }
42
-
43
- set focused(value: boolean) {
44
- this._focused = value;
45
- this.syncFocus();
46
- }
47
-
48
- invalidate(): void {
49
- this.searchInput.invalidate();
50
- }
51
-
52
- handleInput(data: string): void {
53
- if (matchesKey(data, 'shift+tab')) {
54
- this.switchTab(-1);
55
- this.tui.requestRender();
56
- return;
57
- }
58
-
59
- if (this.keybindings.matches(data, 'tui.input.tab')) {
60
- this.switchTab(1);
61
- this.tui.requestRender();
62
- return;
63
- }
64
-
65
- if (this.keybindings.matches(data, 'tui.select.cancel')) {
66
- this.options.onDone(null);
67
- return;
68
- }
69
-
70
- if (this.keybindings.matches(data, 'tui.select.up')) {
71
- this.moveSelection(-1);
72
- this.tui.requestRender();
73
- return;
74
- }
75
-
76
- if (this.keybindings.matches(data, 'tui.select.down')) {
77
- this.moveSelection(1);
78
- this.tui.requestRender();
79
- return;
80
- }
81
-
82
- if (this.keybindings.matches(data, 'tui.select.pageUp')) {
83
- this.moveSelection(-MAX_VISIBLE_MODELS);
84
- this.tui.requestRender();
85
- return;
86
- }
87
-
88
- if (this.keybindings.matches(data, 'tui.select.pageDown')) {
89
- this.moveSelection(MAX_VISIBLE_MODELS);
90
- this.tui.requestRender();
91
- return;
92
- }
93
-
94
- if (this.keybindings.matches(data, 'tui.select.confirm')) {
95
- this.selectCurrentItem();
96
- return;
97
- }
98
-
99
- this.searchInput.handleInput(data);
100
- this.applyFilter(this.searchInput.getValue());
101
- this.tui.requestRender();
102
- }
103
-
104
- render(width: number): string[] {
105
- const safeWidth = Math.max(3, width);
106
-
107
- if (this.options.layout === 'inline') {
108
- const lines = this.buildContentLines(safeWidth);
109
- const rule = this.theme.fg('border', '─'.repeat(safeWidth));
110
- return [rule, ...lines.map(line => this.padLine(line, safeWidth)), rule];
111
- }
112
-
113
- const inner = safeWidth - 2;
114
- const lines = this.buildContentLines(inner);
115
- const borderColor = (str: string) => this.theme.fg('border', str);
116
- const horizontal = '─'.repeat(inner);
117
- const side = borderColor('│');
118
-
119
- return [borderColor(`╭${horizontal}╮`), ...lines.map(line => `${side}${this.padLine(line, inner)}${side}`), borderColor(`╰${horizontal}╯`)];
120
- }
121
-
122
- private createTabs(): DialogTab[] {
123
23
  const definitions: Array<{ identity: TabIdentity; label: string; items: ModelItem[] }> = [
124
- { identity: { kind: 'favourites' }, label: this.options.favouriteLabel, items: this.options.favouriteItems },
24
+ { identity: { kind: 'favourites' }, label: options.favouriteLabel, items: options.favouriteItems },
125
25
  ];
126
-
127
- if (!this.options.hideGroupTabs) {
26
+ if (!options.hideGroupTabs) {
128
27
  definitions.push(
129
- ...this.options.groupLists.map(group => ({
130
- identity: { kind: 'group', name: group.name } as const,
131
- label: group.name,
132
- items: group.items,
133
- })),
28
+ ...options.groupLists.map(group => ({ identity: { kind: 'group', name: group.name } as const, label: group.name, items: group.items })),
134
29
  );
135
30
  }
136
-
137
- if (!this.options.hideSearchTab) {
138
- definitions.push({ identity: { kind: 'search' }, label: 'Search', items: this.options.searchItems });
139
- }
140
-
141
- return definitions.map(definition => {
142
- const currentIndex = this.options.currentModel ? definition.items.findIndex(item => modelsAreEqual(item.model, this.options.currentModel)) : -1;
143
- return {
144
- ...definition,
145
- filteredItems: definition.items,
146
- selectedIndex: currentIndex >= 0 ? currentIndex : 0,
147
- };
148
- });
149
- }
150
-
151
- private applyFilter(query: string): void {
152
- for (const tab of this.tabs) {
153
- tab.filteredItems = this.filterItems(tab.items, query);
154
- tab.selectedIndex = Math.min(tab.selectedIndex, Math.max(0, tab.filteredItems.length - 1));
155
- }
156
- }
157
-
158
- private buildContentLines(inner: number): string[] {
159
- const lines: string[] = [this.line(this.renderTitle(), inner), this.renderTabs(inner)];
160
-
161
- for (const warning of this.options.configWarnings.slice(0, MAX_CONFIG_WARNING_LINES)) {
162
- lines.push(this.line(this.theme.fg('warning', `⚠ ${warning}`), inner));
163
- }
164
- if (this.options.configWarnings.length > MAX_CONFIG_WARNING_LINES) {
165
- lines.push(
166
- this.line(this.theme.fg('warning', `⚠ ${this.options.configWarnings.length - MAX_CONFIG_WARNING_LINES} more config warning(s)`), inner),
167
- );
31
+ if (!options.hideSearchTab) {
32
+ definitions.push({ identity: { kind: 'search' }, label: 'Search', items: options.searchItems });
168
33
  }
169
34
 
170
- lines.push('', ...this.renderActiveTab(inner), '', this.line(this.renderHelp(), inner));
171
- return lines;
172
- }
35
+ const tabs = definitions.map(definition => this.createTab(definition));
36
+ const searchTabIndex = definitions.findIndex(definition => definition.identity.kind === 'search');
173
37
 
174
- private padLine(text: string, innerWidth: number): string {
175
- const truncated = truncateToWidth(text.replace(/[\r\n]+/g, ' '), innerWidth, '');
176
- return truncated + ' '.repeat(Math.max(0, innerWidth - visibleWidth(truncated)));
177
- }
178
-
179
- private switchTab(direction: -1 | 1): void {
180
- this.activeTabIndex = this.wrapIndex(this.activeTabIndex + direction, this.tabs.length);
181
- this.syncFocus();
182
- }
183
-
184
- private syncFocus(): void {
185
- this.searchInput.focused = this._focused;
186
- }
187
-
188
- private moveSelection(delta: number): void {
189
- const tab = this.activeTab();
190
- tab.selectedIndex = this.wrapIndex(tab.selectedIndex + delta, tab.filteredItems.length);
191
- }
192
-
193
- private wrapIndex(index: number, length: number): number {
194
- return length <= 0 ? 0 : ((index % length) + length) % length;
38
+ this.dialog = new ModalDialog<DialogResult>(tui, theme, keybindings, {
39
+ tabs,
40
+ initialTabIndex: options.initialSearch !== '' && searchTabIndex >= 0 ? searchTabIndex : 0,
41
+ title: this.renderTitle(),
42
+ notices: options.configWarnings,
43
+ maxNoticeLines: MAX_CONFIG_WARNING_LINES,
44
+ filter: { initialQuery: options.initialSearch },
45
+ frame: options.layout === 'overlay' ? 'bordered' : 'inline',
46
+ cancelValue: null,
47
+ onComplete: result => options.onDone(result),
48
+ });
195
49
  }
196
50
 
197
- private selectCurrentItem(): void {
198
- const tab = this.activeTab();
199
- const item = tab.filteredItems[tab.selectedIndex];
200
- if (item) {
201
- this.options.onDone(item.model);
202
- }
51
+ get focused(): boolean {
52
+ return this.dialog.focused;
203
53
  }
204
54
 
205
- private activeTab(): DialogTab {
206
- const tab = this.tabs[this.activeTabIndex];
207
- if (!tab) {
208
- throw new Error('Model selector requires at least the Favourites tab');
209
- }
210
- return tab;
55
+ set focused(value: boolean) {
56
+ this.dialog.focused = value;
211
57
  }
212
58
 
213
- private filterItems(items: ModelItem[], query: string): ModelItem[] {
214
- const trimmed = query.trim();
215
- return trimmed ? fuzzyFilter(items, trimmed, item => item.searchText) : items;
59
+ invalidate(): void {
60
+ this.dialog.invalidate();
216
61
  }
217
62
 
218
- private renderTitle(): string {
219
- const current = this.options.currentModel ? ModelFormatter.modelLabel(this.options.currentModel) : 'none';
220
- const reasoning = this.options.defaultReasoning ? ` • reasoning: ${this.options.defaultReasoning}` : '';
221
- return `${this.theme.fg('customMessageLabel', this.theme.bold('Select Model'))} ${this.theme.fg('muted', `current: ${current}${reasoning}`)}`;
63
+ handleInput(data: string): void {
64
+ this.dialog.handleInput(data);
222
65
  }
223
66
 
224
- private renderTabs(width: number): string {
225
- const labels = this.tabs.map(tab => `[${tab.label} ${tab.filteredItems.length}]`);
226
- const separator = ' ';
227
- if (visibleWidth(labels.join(separator)) <= width) {
228
- return this.styleTabLabels(labels, 0, labels.length - 1, false, false);
229
- }
230
-
231
- let start = this.activeTabIndex;
232
- let end = this.activeTabIndex;
233
- let expandLeft = true;
234
- while (true) {
235
- const nextStart = expandLeft && start > 0 ? start - 1 : start;
236
- const nextEnd = !expandLeft && end < labels.length - 1 ? end + 1 : end;
237
- expandLeft = !expandLeft;
238
-
239
- if (nextStart === start && nextEnd === end) {
240
- if ((start === 0 || nextStart === start) && (end === labels.length - 1 || nextEnd === end)) break;
241
- continue;
242
- }
243
-
244
- const candidate = this.plainTabViewport(labels, nextStart, nextEnd);
245
- if (visibleWidth(candidate) <= width) {
246
- start = nextStart;
247
- end = nextEnd;
248
- continue;
249
- }
250
-
251
- const otherStart = start > 0 ? start - 1 : start;
252
- const otherEnd = end < labels.length - 1 ? end + 1 : end;
253
- if ((otherStart === start && otherEnd === end) || visibleWidth(this.plainTabViewport(labels, otherStart, otherEnd)) > width) break;
254
- start = otherStart;
255
- end = otherEnd;
256
- }
257
-
258
- const leftOmitted = start > 0;
259
- const rightOmitted = end < labels.length - 1;
260
- const plain = this.plainTabViewport(labels, start, end);
261
- if (visibleWidth(plain) <= width) {
262
- return this.styleTabLabels(labels, start, end, leftOmitted, rightOmitted);
263
- }
264
-
265
- const prefix = leftOmitted ? '… ' : '';
266
- const suffix = rightOmitted ? ' …' : '';
267
- const activeBudget = Math.max(1, width - visibleWidth(prefix) - visibleWidth(suffix));
268
- const active = truncateToWidth(labels[this.activeTabIndex] ?? '', activeBudget, '');
269
- return this.line(`${this.theme.fg('muted', prefix)}${this.theme.fg('accent', this.theme.bold(active))}${this.theme.fg('muted', suffix)}`, width);
67
+ render(width: number): string[] {
68
+ return this.dialog.render(width);
69
+ }
70
+
71
+ private createTab(definition: { identity: TabIdentity; label: string; items: ModelItem[] }): ModalTab {
72
+ const currentIndex = this.options.currentModel ? definition.items.findIndex(item => modelsAreEqual(item.model, this.options.currentModel)) : -1;
73
+
74
+ return new ListTab<ModelItem>(this.theme, {
75
+ label: counts => `[${definition.label} ${counts.filtered}]`,
76
+ items: definition.items,
77
+ initialIndex: currentIndex >= 0 ? currentIndex : 0,
78
+ wrap: true,
79
+ visibleCount: MAX_VISIBLE_MODELS,
80
+ filterText: item => item.searchText,
81
+ filterCaption: () => this.filterCaption(definition.identity),
82
+ emptyMessage: () => this.emptyMessage(definition),
83
+ noMatchMessage: `No matching ${definition.identity.kind === 'search' ? 'models' : 'favourites'}`,
84
+ renderRow: (item, selected) => this.renderModelItem(item, selected),
85
+ footer: state => this.renderFooter(definition.identity, state.selected),
86
+ onConfirm: item => this.dialog.complete(item.model),
87
+ });
270
88
  }
271
89
 
272
- private plainTabViewport(labels: string[], start: number, end: number): string {
273
- const parts = labels.slice(start, end + 1);
274
- if (start > 0) parts.unshift('…');
275
- if (end < labels.length - 1) parts.push('…');
276
- return parts.join(' ');
90
+ private filterCaption(identity: TabIdentity): string[] {
91
+ if (identity.kind !== 'search') return [this.theme.fg('muted', 'Filter:')];
92
+ const providerText =
93
+ this.options.providerFilter.length === 0 ? 'all authorized providers' : `providers: ${this.options.providerFilter.join(', ')}`;
94
+ return [this.theme.fg('muted', `Provider filter: ${providerText}`), this.theme.fg('muted', 'Search query:')];
277
95
  }
278
96
 
279
- private styleTabLabels(labels: string[], start: number, end: number, leftOmitted: boolean, rightOmitted: boolean): string {
280
- const parts: string[] = [];
281
- if (leftOmitted) parts.push(this.theme.fg('muted', '…'));
282
- for (let index = start; index <= end; index++) {
283
- const label = labels[index] ?? '';
284
- parts.push(index === this.activeTabIndex ? this.theme.fg('accent', this.theme.bold(label)) : this.theme.fg('muted', label));
285
- }
286
- if (rightOmitted) parts.push(this.theme.fg('muted', '…'));
287
- return parts.join(this.theme.fg('muted', ' '));
97
+ private emptyMessage(definition: { identity: TabIdentity; label: string }): string {
98
+ if (definition.identity.kind === 'favourites') return 'No configured favourites are available.';
99
+ if (definition.identity.kind === 'group') return `No available favourites in ${definition.label}.`;
100
+ return 'No matching models';
288
101
  }
289
102
 
290
- private renderActiveTab(width: number): string[] {
291
- const tab = this.activeTab();
103
+ private renderFooter(identity: TabIdentity, selected: ModelItem | undefined): string[] {
292
104
  const lines: string[] = [];
293
-
294
- if (tab.identity.kind === 'search') {
295
- const providerText =
296
- this.options.providerFilter.length === 0 ? 'all authorized providers' : `providers: ${this.options.providerFilter.join(', ')}`;
297
- lines.push(this.line(this.theme.fg('muted', `Provider filter: ${providerText}`), width));
298
- lines.push(this.line(this.theme.fg('muted', 'Search query:'), width));
299
- } else {
300
- lines.push(this.line(this.theme.fg('muted', 'Filter:'), width));
301
- }
302
- lines.push(...this.searchInput.render(width), '');
303
-
304
- if (tab.items.length === 0) {
305
- lines.push(this.line(this.theme.fg('muted', this.emptyTabMessage(tab)), width));
306
- } else if (tab.filteredItems.length === 0) {
307
- lines.push(this.line(this.theme.fg('muted', ` No matching ${tab.identity.kind === 'search' ? 'models' : 'favourites'}`), width));
308
- } else {
309
- lines.push(...this.renderModelList(tab.filteredItems, tab.selectedIndex, width));
310
- const selected = tab.filteredItems[tab.selectedIndex];
311
- if (selected) {
312
- lines.push('', this.line(this.theme.fg('muted', ` ${selected.description}`), width));
105
+ if (selected !== undefined) {
106
+ lines.push('', this.theme.fg('muted', ` ${selected.description}`));
107
+ }
108
+ if (identity.kind === 'favourites') {
109
+ const warnings = this.options.favouriteWarnings;
110
+ const shown = warnings.slice(0, MAX_CONFIG_WARNING_LINES);
111
+ for (const warning of shown) {
112
+ lines.push(this.theme.fg('warning', ` ⚠ ${warning}`));
113
+ }
114
+ if (warnings.length > shown.length) {
115
+ lines.push(this.theme.fg('warning', ` ⚠ ${warnings.length - shown.length} more favourite warning(s)`));
313
116
  }
314
- }
315
-
316
- if (tab.identity.kind === 'favourites') {
317
- this.appendFavouriteWarnings(lines, width);
318
- }
319
- return lines;
320
- }
321
-
322
- private emptyTabMessage(tab: DialogTab): string {
323
- if (tab.identity.kind === 'favourites') return ' No configured favourites are available.';
324
- if (tab.identity.kind === 'group') return ` No available favourites in ${tab.label}.`;
325
- return ' No matching models';
326
- }
327
-
328
- private appendFavouriteWarnings(lines: string[], width: number): void {
329
- for (const warning of this.options.favouriteWarnings.slice(0, MAX_CONFIG_WARNING_LINES)) {
330
- lines.push(this.line(this.theme.fg('warning', ` ⚠ ${warning}`), width));
331
- }
332
- if (this.options.favouriteWarnings.length > MAX_CONFIG_WARNING_LINES) {
333
- lines.push(
334
- this.line(
335
- this.theme.fg('warning', ` ⚠ ${this.options.favouriteWarnings.length - MAX_CONFIG_WARNING_LINES} more favourite warning(s)`),
336
- width,
337
- ),
338
- );
339
- }
340
- }
341
-
342
- private renderModelList(items: ModelItem[], selectedIndex: number, width: number): string[] {
343
- const startIndex = Math.max(0, Math.min(selectedIndex - Math.floor(MAX_VISIBLE_MODELS / 2), items.length - MAX_VISIBLE_MODELS));
344
- const endIndex = Math.min(startIndex + MAX_VISIBLE_MODELS, items.length);
345
- const lines: string[] = [];
346
-
347
- for (let index = startIndex; index < endIndex; index++) {
348
- const item = items[index];
349
- if (item) lines.push(this.renderModelItem(item, index === selectedIndex, width));
350
- }
351
- if (startIndex > 0 || endIndex < items.length) {
352
- lines.push(this.line(this.theme.fg('dim', ` (${selectedIndex + 1}/${items.length})`), width));
353
117
  }
354
118
  return lines;
355
119
  }
356
120
 
357
- private renderModelItem(item: ModelItem, isSelected: boolean, width: number): string {
121
+ private renderModelItem(item: ModelItem, isSelected: boolean): string {
358
122
  const currentMark = modelsAreEqual(item.model, this.options.currentModel) ? this.theme.fg('success', ' ✓') : '';
359
123
  const providerBadge = this.theme.fg('muted', `[${item.model.provider}]`);
360
124
  const prefix = isSelected ? this.theme.fg('accent', '→ ') : ' ';
361
125
  const modelText = isSelected ? this.theme.fg('accent', item.model.id) : item.model.id;
362
- return this.line(`${prefix}${modelText} ${providerBadge}${currentMark}`, width);
363
- }
364
-
365
- private renderHelp(): string {
366
- const tabHint = this.tabs.length > 1 ? 'tab/shift+tab switch sections • ' : '';
367
- return this.theme.fg('dim', `${tabHint}↑↓ navigate • enter select • esc cancel`);
126
+ return `${prefix}${modelText} ${providerBadge}${currentMark}`;
368
127
  }
369
128
 
370
- private line(text: string, width: number): string {
371
- return truncateToWidth(text.replace(/[\r\n]+/g, ' '), Math.max(1, width), '');
129
+ private renderTitle(): string {
130
+ const current = this.options.currentModel ? ModelFormatter.modelLabel(this.options.currentModel) : 'none';
131
+ const reasoning = this.options.defaultReasoning ? ` • reasoning: ${this.options.defaultReasoning}` : '';
132
+ return `${this.theme.fg('customMessageLabel', this.theme.bold('Select Model'))} ${this.theme.fg('muted', `current: ${current}${reasoning}`)}`;
372
133
  }
373
134
  }
@@ -4,7 +4,14 @@
4
4
 
5
5
  `src/libs/` hosts shared, domain-specific library modules that are consumed by extensions and features across the project. It is not a generic utilities folder; modules here encapsulate cohesive business capabilities with stable public APIs.
6
6
 
7
- Currently, the folder contains the `subscription-usage` module, whose job is to fetch and normalize subscription/rate-limit usage data from upstream OAuth providers (Anthropic, OpenAI Codex) so that UI code can display a consistent usage indicator without needing to know provider-specific API details.
7
+ Currently, the folder contains two modules: the `subscription-usage` module, which fetches and normalizes subscription/rate-limit usage data from upstream OAuth providers (Anthropic, OpenAI Codex) so UI code can display a consistent usage indicator without knowing provider-specific API details; and the `modal` module, a self-contained modal dialog library (shell, navigation schemes, tab strategies, preview layers, list navigation, text helpers) consumed by the `model-select` and `context-view` extensions and copy-portable to other Pi plugins.
8
+
9
+ ## Directory Map
10
+
11
+ | Directory | Responsibility Summary | Detailed Map |
12
+ | --- | --- | --- |
13
+ | `subscription-usage/` | Provider-agnostic subscription/rate-limit usage access behind strategies and a facade. | [View Map](subscription-usage/codemap.md) |
14
+ | `modal/` | Shared modal dialog shell, navigation schemes, tab strategies, layers, and layout helpers. | [View Map](modal/codemap.md) |
8
15
 
9
16
  ## Design Patterns
10
17