@0xkahi/pi-qol 1.1.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +12 -3
  2. package/assets/config.schema.json +2 -18
  3. package/package.json +4 -4
  4. package/src/extensions/custom-footer/codemap.md +5 -6
  5. package/src/extensions/custom-footer/constants.ts +0 -1
  6. package/src/extensions/custom-footer/footer-component.ts +19 -9
  7. package/src/extensions/custom-footer/index.ts +3 -1
  8. package/src/extensions/custom-footer/token-stats.ts +25 -17
  9. package/src/extensions/custom-footer/types.ts +3 -1
  10. package/src/extensions/model-select/codemap.md +8 -4
  11. package/src/extensions/model-select/index.ts +35 -29
  12. package/src/extensions/model-select/model-select-dialog.ts +9 -25
  13. package/src/extensions/model-select/model-select-modal.ts +66 -0
  14. package/src/extensions/model-select/usage-section/codemap.md +14 -0
  15. package/src/extensions/model-select/usage-section/index.ts +37 -0
  16. package/src/extensions/model-select/usage-section/usage-provider-tab.ts +166 -0
  17. package/src/index.ts +7 -3
  18. package/src/libs/modal/README.md +46 -2
  19. package/src/libs/modal/codemap.md +4 -1
  20. package/src/libs/modal/index.ts +2 -0
  21. package/src/libs/modal/label-window.ts +32 -0
  22. package/src/libs/modal/modal-dialog.ts +16 -2
  23. package/src/libs/modal/section-strip.ts +33 -0
  24. package/src/libs/modal/sectioned-modal.ts +105 -0
  25. package/src/libs/modal/tab-strip.ts +2 -26
  26. package/src/libs/subscription-usage/codemap.md +10 -21
  27. package/src/libs/subscription-usage/credential-resolver.ts +44 -0
  28. package/src/libs/subscription-usage/index.ts +8 -0
  29. package/src/libs/subscription-usage/pace.ts +28 -0
  30. package/src/libs/subscription-usage/progress-bar.ts +13 -0
  31. package/src/libs/subscription-usage/provider-color.ts +10 -0
  32. package/src/libs/subscription-usage/strategy/anthropic-oauth-usage.strategy.ts +5 -5
  33. package/src/libs/subscription-usage/strategy/codemap.md +5 -41
  34. package/src/libs/subscription-usage/strategy/openai-codex-usage.strategy.ts +7 -8
  35. package/src/libs/subscription-usage/subscription-usage-api.util.ts +45 -66
  36. package/src/libs/subscription-usage/subscription-usage-cache.ts +89 -0
  37. package/src/schemas/codemap.md +1 -1
  38. package/src/schemas/custom-footer-config.schema.ts +0 -4
  39. package/src/extensions/custom-footer/progress-bar.ts +0 -16
  40. package/src/extensions/custom-footer/subscription-usage-manager.ts +0 -91
@@ -0,0 +1,14 @@
1
+ # src/extensions/model-select/usage-section/
2
+
3
+ ## Responsibility
4
+
5
+ Read-only subscription usage section of the model selector, consuming the same injected cache as the custom footer.
6
+
7
+ ## Modules
8
+
9
+ - `index.ts`: `createUsageSection` builds an embedded Vim-navigated dialog with bracketed `[Claude]`/`[Codex]` tabs, preselects the current supported provider (else Claude), and requests every provider on first activation through the section host.
10
+ - `usage-provider-tab.ts`: `UsageProviderTab` renders provider status, freshness, all rate windows, progress/reset/pace rows, and retained row navigation using `ListNavigator`. Failures preserve last-success windows and their original fetch time. Raw `r` forces active-provider refresh. The injected clock keeps relative times testable. Window rows have one blank separator, with `ListNavigator` still selecting windows rather than separator lines; bounded views budget two lines per visible window minus the final separator. Provider names, labels, bar fills, and percentages use the fixed `providerUsageColor` palette from the subscription-usage library and cli-dye; empty bars and reset text are dim. Model-select does not depend on footer internals or color configuration. The render cache keys on whole seconds, result, in-flight state, last success, and viewport, while navigation/theme changes invalidate it. In-flight fetches with displayed windows show `refreshing…` and retain the rows.
11
+
12
+ ## Lifecycle
13
+
14
+ `ModelSelectModal` owns the cache subscription and a 1s interval that requests renders only while Usage is active. Either section's completion or host `dispose()` clears both resources through idempotent cleanup. Select Model alone never fetches usage or requests timed renders. Cache completion requests a render; visible ticks update freshness and reset countdowns without input.
@@ -0,0 +1,37 @@
1
+ import type { KeybindingsManager, Theme } from '@earendil-works/pi-coding-agent';
2
+ import type { TUI } from '@earendil-works/pi-tui';
3
+ import { ModalDialog, type ModalSection, VimNavigationScheme } from '../../../libs/modal';
4
+ import { resolveSupportedProvider, SUBSCRIPTION_PROVIDERS, type SubscriptionUsageCache } from '../../../libs/subscription-usage';
5
+ import type { DialogResult } from '../types';
6
+ import { UsageProviderTab } from './usage-provider-tab';
7
+
8
+ export function createUsageSection(
9
+ tui: TUI,
10
+ theme: Theme,
11
+ keybindings: KeybindingsManager,
12
+ options: {
13
+ cache: SubscriptionUsageCache;
14
+ currentProvider?: string;
15
+ onDone: (result: DialogResult) => void;
16
+ now?: () => number;
17
+ },
18
+ ): ModalSection<DialogResult> {
19
+ const provider = resolveSupportedProvider(options.currentProvider);
20
+ return {
21
+ label: 'Usage',
22
+ dialog: new ModalDialog<DialogResult>(tui, theme, keybindings, {
23
+ tabs: SUBSCRIPTION_PROVIDERS.map(entry => new UsageProviderTab(theme, options.cache, entry.provider, entry.label, options.now)),
24
+ initialTabIndex: Math.max(
25
+ 0,
26
+ SUBSCRIPTION_PROVIDERS.findIndex(entry => entry.provider === provider),
27
+ ),
28
+ navigation: new VimNavigationScheme(),
29
+ frame: 'none',
30
+ cancelValue: null,
31
+ onComplete: options.onDone,
32
+ }),
33
+ onActivate: () => {
34
+ for (const entry of SUBSCRIPTION_PROVIDERS) options.cache.ensureFresh(entry.provider);
35
+ },
36
+ };
37
+ }
@@ -0,0 +1,166 @@
1
+ import { dye } from '@0xkahi/cli-dye';
2
+ import type { Theme } from '@earendil-works/pi-coding-agent';
3
+ import { matchesKey, visibleWidth } from '@earendil-works/pi-tui';
4
+ import { type Hint, ListNavigator, type ModalTab, type NavigationAction, padLine, RenderCache, singleLine, spreadLine } from '../../../libs/modal';
5
+ import {
6
+ clampPercent,
7
+ computePace,
8
+ formatResetDescription,
9
+ providerUsageColor,
10
+ type RateWindow,
11
+ renderProgressBar,
12
+ type SubscriptionProvider,
13
+ type SubscriptionUsageCache,
14
+ type UsageCacheEntry,
15
+ type UsageResult,
16
+ } from '../../../libs/subscription-usage';
17
+
18
+ function statusMessage(result: UsageResult | undefined): string | undefined {
19
+ switch (result?.status) {
20
+ case 'ok':
21
+ return undefined;
22
+ case 'no-auth':
23
+ return 'not logged in';
24
+ case 'expired':
25
+ return 'auth expired, re-login';
26
+ case 'http-error':
27
+ return `request failed (HTTP ${result.httpStatus})`;
28
+ case 'network':
29
+ return 'network error';
30
+ case 'unavailable':
31
+ return 'no usage data';
32
+ default:
33
+ return 'loading';
34
+ }
35
+ }
36
+
37
+ function freshness(fetchedAt: number, now: number): string {
38
+ const seconds = Math.max(0, Math.floor((now - fetchedAt) / 1000));
39
+ const age = seconds < 60 ? `${seconds}s` : seconds < 3600 ? `${Math.floor(seconds / 60)}m` : `${Math.floor(seconds / 3600)}h`;
40
+ return `updated ${age} ago`;
41
+ }
42
+
43
+ export class UsageProviderTab implements ModalTab {
44
+ private readonly navigator = new ListNavigator(0, 1);
45
+ private readonly renderCache = new RenderCache();
46
+ private renderedAt: number | undefined;
47
+ private renderedResult: UsageResult | undefined;
48
+ private renderedInFlight: boolean | undefined;
49
+ private renderedSuccess: UsageCacheEntry['lastSuccess'];
50
+
51
+ public constructor(
52
+ private readonly theme: Theme,
53
+ private readonly cache: SubscriptionUsageCache,
54
+ public readonly provider: SubscriptionProvider,
55
+ private readonly providerName: string,
56
+ private readonly now: () => number = Date.now,
57
+ ) {}
58
+
59
+ public get label(): string {
60
+ return `[${this.providerName}]`;
61
+ }
62
+
63
+ public render(width: number, height: number | undefined): string[] {
64
+ const entry = this.cache.get(this.provider);
65
+ const windows = this.windows();
66
+ const now = this.now();
67
+ const second = Math.floor(now / 1000);
68
+ const color = providerUsageColor(this.provider);
69
+ if (
70
+ second !== this.renderedAt ||
71
+ entry?.result !== this.renderedResult ||
72
+ entry?.inFlight !== this.renderedInFlight ||
73
+ entry?.lastSuccess !== this.renderedSuccess
74
+ )
75
+ this.invalidate();
76
+ this.renderedAt = second;
77
+ this.renderedResult = entry?.result;
78
+ this.renderedInFlight = entry?.inFlight;
79
+ this.renderedSuccess = entry?.lastSuccess;
80
+ const cached = this.renderCache.read(width, height);
81
+ if (cached !== undefined) return [...cached];
82
+ const status = entry?.inFlight && windows.length > 0 ? 'refreshing…' : statusMessage(entry?.result);
83
+ const updated = entry?.lastSuccess === undefined ? undefined : freshness(entry.lastSuccess.fetchedAt, now);
84
+ const header = spreadLine(
85
+ this.theme.bold(dye.colorize(this.providerName, { fg: dye.hex(color) })),
86
+ this.theme.fg('muted', status ?? updated ?? ''),
87
+ width,
88
+ );
89
+ const lines = [header];
90
+ if (status !== undefined && updated !== undefined) lines.push(this.theme.fg('muted', updated));
91
+ lines.push('');
92
+ // Keep the selected window visible even when there is no room for chrome.
93
+ if (height !== undefined) lines.length = Math.min(lines.length, Math.max(0, height - 1));
94
+ const available = height === undefined ? windows.length * 2 - 1 : height - lines.length;
95
+ this.navigator.setRowCount(windows.length);
96
+ this.navigator.setVisibleCount(Math.max(1, Math.floor((available + 1) / 2)));
97
+ const labelWidth = Math.max(0, ...windows.map(window => visibleWidth(window.label)));
98
+ for (let index = this.navigator.offset; index < this.navigator.visibleEnd; index++) {
99
+ const window = windows[index];
100
+ if (window !== undefined) {
101
+ if (index > this.navigator.offset) lines.push('');
102
+ lines.push(singleLine(this.renderWindow(window, index === this.navigator.selected, labelWidth, now, color), width));
103
+ }
104
+ }
105
+ const fitted = lines.map(line => singleLine(line, width));
106
+ return [...this.renderCache.write(width, height, fitted)];
107
+ }
108
+
109
+ public invalidate(): void {
110
+ this.renderCache.clear();
111
+ }
112
+
113
+ public handleInput(data: string): void {
114
+ if (matchesKey(data, 'r')) this.cache.refresh(this.provider);
115
+ this.invalidate();
116
+ }
117
+
118
+ public handleNavigation(action: NavigationAction): void {
119
+ this.invalidate();
120
+ this.navigator.setRowCount(this.windows().length);
121
+ switch (action) {
122
+ case 'step-back':
123
+ this.navigator.moveBy(-1);
124
+ break;
125
+ case 'step-forward':
126
+ this.navigator.moveBy(1);
127
+ break;
128
+ case 'page-back':
129
+ this.navigator.page(-1);
130
+ break;
131
+ case 'page-forward':
132
+ this.navigator.page(1);
133
+ break;
134
+ case 'first':
135
+ this.navigator.moveTo(0);
136
+ break;
137
+ case 'last':
138
+ this.navigator.moveTo(this.navigator.selectableCount - 1);
139
+ break;
140
+ }
141
+ }
142
+
143
+ public hints(): Hint[] {
144
+ return [['r', 'Refresh']];
145
+ }
146
+
147
+ private windows(): RateWindow[] {
148
+ const entry = this.cache.get(this.provider);
149
+ return entry?.result?.status === 'ok' ? entry.result.windows : (entry?.lastSuccess?.windows ?? []);
150
+ }
151
+
152
+ private renderWindow(window: RateWindow, selected: boolean, labelWidth: number, now: number, color: string): string {
153
+ const foreground = dye.hex(color);
154
+ const colorize = (text: string) => dye.colorize(text, { fg: foreground });
155
+ const bar = renderProgressBar(window.usedPercent);
156
+ const progress = colorize(bar.filled) + this.theme.fg('dim', bar.empty);
157
+ const reset = window.resetAt === undefined ? '' : this.theme.fg('dim', ` resets ${formatResetDescription(window.resetAt, now)}`);
158
+ const pace = computePace(window, now)?.pace;
159
+ const paceText =
160
+ pace === undefined
161
+ ? ''
162
+ : ` ${this.theme.fg(pace === 'ahead' ? 'warning' : pace === 'limit' ? 'error' : 'muted', pace === 'on-pace' ? 'on pace' : pace)}`;
163
+ const marker = selected ? this.theme.fg('accent', '→ ') : ' ';
164
+ return `${marker}${colorize(padLine(window.label, labelWidth))} ${progress} ${colorize(`${Math.round(clampPercent(window.usedPercent))}%`)}${reset}${paceText}`;
165
+ }
166
+ }
package/src/index.ts CHANGED
@@ -1,22 +1,26 @@
1
- import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
1
+ import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
2
2
  import { ConfigLoader } from './config-loader';
3
3
  import { registerAutoSessionName } from './extensions/auto-session-name';
4
4
  import { registerContextView } from './extensions/context-view';
5
5
  import { registerCustomFooter } from './extensions/custom-footer';
6
6
  import { registerModelSelect } from './extensions/model-select';
7
7
  import { registerWorkmux } from './extensions/workmux';
8
+ import { createHostCredentialResolver, SubscriptionUsageApi, SubscriptionUsageCache } from './libs/subscription-usage';
8
9
 
9
10
  export default function (pi: ExtensionAPI) {
10
11
  const config = new ConfigLoader();
12
+ let latestCtx: ExtensionContext | undefined;
13
+ const usageCache = new SubscriptionUsageCache({ api: new SubscriptionUsageApi(createHostCredentialResolver(() => latestCtx)) });
11
14
 
12
15
  pi.on('session_start', (_event, ctx) => {
16
+ latestCtx = ctx;
13
17
  const { error } = config.initializeConfig(ctx);
14
18
  if (error) ctx.ui.notify(error, 'error');
15
19
  });
16
20
 
17
21
  registerAutoSessionName(pi, { config });
18
- registerModelSelect(pi, { config });
19
- registerCustomFooter(pi, { config });
22
+ registerModelSelect(pi, { config, usageCache });
23
+ registerCustomFooter(pi, { config, usageCache });
20
24
  registerContextView(pi, { config });
21
25
  registerWorkmux(pi, { config });
22
26
  }
@@ -69,6 +69,48 @@ Three interfaces cover all content:
69
69
  - **`ModalLayer`** — full-content overlay above a tab (usually the pre-built `PreviewLayer`). Each tab has its **own** layer stack: Tab-switching works while a layer is open, and each tab restores its layer when you return.
70
70
  - **`NavigationScheme`** — pure key→action mapper. Default: `PiKeybindingsScheme` (follows the user's `tui.select.*` remappings). Alternative: `VimNavigationScheme` (`j/k`, `Ctrl+u/d`, `gg/G`, `q`) for read-only inspectors.
71
71
 
72
+ ## Sections
73
+
74
+ ```
75
+ Modal (frame + section rule)
76
+ > Section (retained embedded ModalDialog, scheme, filter, hints)
77
+ > Tab (selection, scroll, content)
78
+ > Layer (preview stack)
79
+ ```
80
+
81
+ `SectionedModal` owns the frame (`SectionFrame = 'inline' | 'bordered'`);
82
+ build each section dialog with `frame: 'none'`. Consumers owning subscriptions or
83
+ timers should clean them up from both completion and an idempotent `dispose()`
84
+ method, which Pi calls when the component closes.
85
+ Wire every dialog's `onComplete` to the same host `done` callback and choose its
86
+ `cancelValue`. Section state survives switches, and natural height follows the
87
+ active section. `onActivate` runs once per section, including the initial section.
88
+
89
+ Input routing: `Ctrl+]` goes forward and disambiguated `Ctrl+[` goes backward
90
+ (both wrap); all other input goes to the active dialog. Bare Esc always dismisses
91
+ through that dialog (layers close first). In non-Kitty terminals, `Ctrl+[` is Esc.
92
+ Tab/Shift+Tab stay inside the section. Switching clears pending navigation chords.
93
+ Only the active dialog receives focus. Multiple sections add a footer hint.
94
+
95
+ ```ts
96
+ await presentModal(ctx.ui, layout, (tui, theme, keybindings, done, frame) => {
97
+ const picker = new ModalDialog(tui, theme, keybindings, {
98
+ tabs: pickerTabs, frame: 'none', filter: {},
99
+ cancelValue: null, onComplete: done,
100
+ });
101
+ const usage = new ModalDialog(tui, theme, keybindings, {
102
+ tabs: usageTabs, frame: 'none', navigation: new VimNavigationScheme(),
103
+ cancelValue: null, onComplete: done,
104
+ });
105
+ return new SectionedModal(tui, theme, {
106
+ frame, sections: [
107
+ { label: 'Select', dialog: picker },
108
+ { label: 'Usage', dialog: usage, onActivate: loadUsage },
109
+ ],
110
+ });
111
+ });
112
+ ```
113
+
72
114
  ## Recipes
73
115
 
74
116
  ### Filterable picker (model-select style)
@@ -191,7 +233,7 @@ await presentModal(ctx.ui, layout, (tui, theme, keybindings, done, frame) =>
191
233
  | --- | --- | --- | --- |
192
234
  | `tabs` | `ModalTab[]` | required | ≥1 tab; first is active unless `initialTabIndex` |
193
235
  | `navigation` | `NavigationScheme` | `PiKeybindingsScheme` | key→action mapping |
194
- | `frame` | `'inline' \| 'bordered'` | `'inline'` | rules vs rounded border |
236
+ | `frame` | `'inline' \| 'bordered' \| 'none'` | `'inline'` | rules, rounded border, or embedded content |
195
237
  | `height` | `'auto' \| 'half'` | `'auto'` | bound to half terminal |
196
238
  | `title` | `string \| () => string` | — | line above the tab strip |
197
239
  | `notices` | `string[] \| () => string[]` | — | `⚠` warning lines below the strip |
@@ -199,7 +241,9 @@ await presentModal(ctx.ui, layout, (tui, theme, keybindings, done, frame) =>
199
241
  | `filter` | `{ initialQuery? }` | — | shared text input; calls `tab.applyFilter` |
200
242
  | `cancelValue` / `onComplete` | `TResult` / callback | required | dismissal result + sink |
201
243
 
202
- Methods: `complete(result)`, `handleInput(data)`, `render(width)`, `invalidate()`, `focused`, `activeTab`, `activeIndex`.
244
+ `extraHints?: Hint[] | (() => Hint[])` inserts footer hints before Esc.
245
+
246
+ Methods: `complete(result)`, `setExtraHints(hints)`, `resetNavigation()`, `handleInput(data)`, `render(width)`, `invalidate()`, `focused`, `activeTab`, `activeIndex`.
203
247
 
204
248
  ### `ListTab<T>` options
205
249
 
@@ -9,13 +9,16 @@ The library is self-contained: it imports only from Pi host packages (`@earendil
9
9
  ## Module Roles
10
10
 
11
11
  - `types.ts` — Contracts: `NavigationAction`/`NavigationResult`/`NavigationScheme` (pure key→action mappers), `ModalTab` (content strategy), `ModalLayer`, `ModalTabContext` (`pushLayer`), `Hint`.
12
- - `modal-dialog.ts` — `ModalDialog<TResult>` shell (`Component + Focusable`). Options: tabs, initial tab, navigation scheme (default `PiKeybindingsScheme`), frame (`inline` rules | `bordered` rounded border), height (`auto` | `half` terminal), title, notices (+ cap), filter, cancel value, completion callback. Routes input: tab cycling (`Tab`/`Shift+Tab`, wrapping, scheme reset) → scheme action (`dismiss` pops the active tab's layer stack or completes with the cancel value; other actions go to the top layer, else active tab) → raw keys (top layer, else filter input, else active tab). Renders frame, strip, notices, filter slot, content region (exact height when bounded), and a footer composed of scheme + tab/layer hints + universal hints. `complete(result)` resolves explicit results (for example selections).
12
+ - `modal-dialog.ts` — `ModalDialog<TResult>` shell (`Component + Focusable`). Options: tabs, initial tab, navigation scheme (default `PiKeybindingsScheme`), frame (`inline` rules | `bordered` rounded border | `none` embedded content), height (`auto` | `half` terminal), title, notices (+ cap), filter, cancel value, completion callback. Routes input: tab cycling (`Tab`/`Shift+Tab`, wrapping, scheme reset) → scheme action (`dismiss` pops the active tab's layer stack or completes with the cancel value; other actions go to the top layer, else active tab) → raw keys (top layer, else filter input, else active tab). Renders frame, strip, notices, filter slot, content region (exact height when bounded), and a footer composed of scheme + tab/layer hints + universal hints. `complete(result)` resolves explicit results (for example selections). `extraHints`/`setExtraHints` insert footer hints before Esc; `resetNavigation()` clears pending chords.
13
13
  - `presenter.ts` — `presentModal<TResult>` and `ModalLayout`: host-facing presenter that maps semantic inline/overlay layouts to the renderer frame and Pi custom-UI mounting options (centered 85%-width overlay with one-cell margin).
14
14
  - `navigation/pi-scheme.ts` — `PiKeybindingsScheme`: maps host `tui.select.*` keybindings to actions (default scheme; stateless).
15
15
  - `navigation/vim-scheme.ts` — `VimNavigationScheme`: `j/k`/arrows, `Ctrl+u/d`, `gg/G` chord (cleared by `reset()`), Enter confirm, Esc/`q` dismiss; swallows PageUp/PageDown/Home/End. For read-only inspectors; do not combine with a filter input.
16
16
  - `tabs/list-tab.ts` — `ListTab<T>` generic picker tab: items + row renderer + confirm callback, optional fuzzy filtering (`filterText`) wired to the dialog filter, dynamic count labels, filter captions, footer hook (rendered below the list in all states), empty/no-match messages, fixed or height-driven window, clamp (default) or wrap selection.
17
17
  - `preview-layer.ts` — `PreviewLayer`: title + right-aligned meta header, `PreviewScroller`-windowed body, overflow counter, optional pinned description; dismissal is shell-owned (pops the layer).
18
18
  - `list-navigator.ts` — `ListNavigator` (selection + scroll window; clamp default, `wrap` option; `setRowCount` for filtered lists) and `PreviewScroller` (scroll-only window over wrapped lines). Forked from `pi-context-view`.
19
+ - `sectioned-modal.ts` — Exports `SectionFrame` (`inline` | `bordered`) for section host framing. `SectionedModal<TResult>` hosts retained `ModalSection` dialogs with `frame: 'none'`, draws the frame, routes Ctrl+]/disambiguated Ctrl+[ before dialog input, resets outgoing navigation, propagates active-only focus, and runs first-activation callbacks. Callers wire every dialog completion to the same host sink and own resource cleanup (for example an idempotent `dispose()` on a consumer subclass). Bare Esc stays dialog input; Tab stays within sections; natural height follows the active dialog.
20
+ - `section-strip.ts` — `renderSectionRule` draws active/inactive section labels in the top rule or rounded border, adding no height.
21
+ - `label-window.ts` — Shared active-centered overflow window computation for tab and section strips.
19
22
  - `tab-strip.ts` — Width-aware tab strip: active label highlighted; overflow keeps a window around the active tab with `…` omission indicators. Labels are re-read each render.
20
23
  - `text.ts` — Pure helpers: `fitLine`, `singleLine`, `padLine`, `spreadLine`, `hintRow`, `wrapDescriptionLines`, `calculateViewport`, `fitToTerminalHeight`, `normalizeTerminalRows`, `BODY_INDENT`, `STEP_KEY_HINT`. Forked from `pi-context-view`.
21
24
  - `render-cache.ts` — `RenderCache`: width/height-keyed frame cache (`read`/`write`/`clear`) for stateful tabs.
@@ -10,6 +10,8 @@ export { VimNavigationScheme } from './navigation/vim-scheme';
10
10
  export { type ModalComponentFactory, type ModalLayout, presentModal } from './presenter';
11
11
  export { PreviewLayer, type PreviewLayerOptions } from './preview-layer';
12
12
  export { RenderCache } from './render-cache';
13
+ export { renderSectionRule } from './section-strip';
14
+ export { type ModalSection, SectionedModal, type SectionFrame } from './sectioned-modal';
13
15
  export { renderTabStrip } from './tab-strip';
14
16
  export { ListTab, type ListTabCounts, type ListTabFooterState, type ListTabOptions } from './tabs/list-tab';
15
17
  export {
@@ -0,0 +1,32 @@
1
+ import { visibleWidth } from '@earendil-works/pi-tui';
2
+
3
+ /** Shared active-centered window for tab and section strips. */
4
+ export function labelWindow(labels: string[], activeIndex: number, width: number, separator: string): { start: number; end: number } {
5
+ const measure = (start: number, end: number): number => {
6
+ const parts = labels.slice(start, end + 1);
7
+ if (start > 0) parts.unshift('…');
8
+ if (end < labels.length - 1) parts.push('…');
9
+ return visibleWidth(parts.join(separator));
10
+ };
11
+ if (visibleWidth(labels.join(separator)) <= width) return { start: 0, end: labels.length - 1 };
12
+ let start = activeIndex;
13
+ let end = activeIndex;
14
+ let expandLeft = true;
15
+ while (true) {
16
+ const nextStart = expandLeft && start > 0 ? start - 1 : start;
17
+ const nextEnd = !expandLeft && end < labels.length - 1 ? end + 1 : end;
18
+ expandLeft = !expandLeft;
19
+ if (nextStart === start && nextEnd === end) break;
20
+ if (measure(nextStart, nextEnd) <= width) {
21
+ start = nextStart;
22
+ end = nextEnd;
23
+ continue;
24
+ }
25
+ const otherStart = start > 0 ? start - 1 : start;
26
+ const otherEnd = end < labels.length - 1 ? end + 1 : end;
27
+ if ((otherStart === start && otherEnd === end) || measure(otherStart, otherEnd) > width) break;
28
+ start = otherStart;
29
+ end = otherEnd;
30
+ }
31
+ return { start, end };
32
+ }
@@ -21,7 +21,7 @@ import { fitToTerminalHeight, hintRow, normalizeTerminalRows, padLine, singleLin
21
21
  import type { Hint, ModalLayer, ModalTab, NavigationScheme } from './types';
22
22
 
23
23
  /** Framing style: inline rules, or a rounded border for host-centered overlays. */
24
- export type ModalFrame = 'inline' | 'bordered';
24
+ export type ModalFrame = 'inline' | 'bordered' | 'none';
25
25
 
26
26
  /** Height policy: natural content height, or bounded to half the terminal. */
27
27
  export type ModalHeight = 'auto' | 'half';
@@ -37,6 +37,8 @@ export interface ModalDialogOptions<TResult> {
37
37
  /** Navigation scheme; defaults to the host keybindings scheme. */
38
38
  navigation?: NavigationScheme;
39
39
  frame?: ModalFrame;
40
+ /** Additional footer hints, inserted before Esc. */
41
+ extraHints?: Hint[] | (() => Hint[]);
40
42
  height?: ModalHeight;
41
43
  /** Optional title line rendered above the tab strip. */
42
44
  title?: string | (() => string);
@@ -59,6 +61,7 @@ export class ModalDialog<TResult> implements Component, Focusable {
59
61
  private readonly layerStacks = new Map<ModalTab, ModalLayer[]>();
60
62
  private activeTabIndex: number;
61
63
  private _focused = false;
64
+ private extraHints: Hint[] | (() => Hint[]);
62
65
 
63
66
  public constructor(
64
67
  private readonly tui: TUI,
@@ -70,6 +73,7 @@ export class ModalDialog<TResult> implements Component, Focusable {
70
73
  this.scheme = options.navigation ?? new PiKeybindingsScheme(keybindings);
71
74
  this.frame = options.frame ?? 'inline';
72
75
  this.height = options.height ?? 'auto';
76
+ this.extraHints = options.extraHints ?? [];
73
77
  this.activeTabIndex = Math.min(Math.max(0, options.initialTabIndex ?? 0), options.tabs.length - 1);
74
78
 
75
79
  for (const tab of options.tabs) {
@@ -118,6 +122,14 @@ export class ModalDialog<TResult> implements Component, Focusable {
118
122
  this.options.onComplete(result);
119
123
  }
120
124
 
125
+ public setExtraHints(hints: Hint[]): void {
126
+ this.extraHints = hints;
127
+ }
128
+
129
+ public resetNavigation(): void {
130
+ this.scheme.reset();
131
+ }
132
+
121
133
  public handleInput(data: string): void {
122
134
  if (this.options.tabs.length > 1) {
123
135
  if (matchesKey(data, Key.shift('tab'))) {
@@ -163,7 +175,8 @@ export class ModalDialog<TResult> implements Component, Focusable {
163
175
  const rule = this.theme.fg('border', '─'.repeat(safeWidth));
164
176
  const lines = [rule, ...this.buildContentLines(safeWidth, this.contentHeight()), rule];
165
177
  const budget = this.heightBudget();
166
- return budget === undefined ? lines : fitToTerminalHeight(lines, budget, rule);
178
+ const fitted = budget === undefined ? lines : fitToTerminalHeight(lines, budget, rule);
179
+ return this.frame === 'none' ? fitted.slice(1, -1) : fitted;
167
180
  }
168
181
 
169
182
  // === Input routing internals ===
@@ -291,6 +304,7 @@ export class ModalDialog<TResult> implements Component, Focusable {
291
304
  const target = layer ?? this.activeTab;
292
305
  const hints: Hint[] = [...this.scheme.hints(layer === undefined ? 'Navigate' : 'Scroll'), ...target.hints()];
293
306
  if (this.options.tabs.length > 1) hints.push(['Tab', 'Switch']);
307
+ hints.push(...(typeof this.extraHints === 'function' ? this.extraHints() : this.extraHints));
294
308
  hints.push(['Esc', layer === undefined ? 'Close' : 'Back']);
295
309
  return hints;
296
310
  }
@@ -0,0 +1,33 @@
1
+ import type { Theme } from '@earendil-works/pi-coding-agent';
2
+ import { truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
3
+ import { labelWindow } from './label-window';
4
+
5
+ /** Render section labels inside the frame's top rule without adding height. */
6
+ export function renderSectionRule(theme: Theme, labels: string[], activeIndex: number, width: number, style: 'inline' | 'bordered'): string {
7
+ const safeWidth = Math.max(0, Math.floor(width));
8
+ const border = (text: string) => theme.fg('border', text);
9
+ const bordered = style === 'bordered' && safeWidth >= 2;
10
+ const inner = safeWidth - (bordered ? 2 : 0);
11
+ const separator = bordered ? ' ─ ' : ' ── ';
12
+ const prefix = bordered ? '─ ' : '── ';
13
+ const budget = Math.max(0, inner - visibleWidth(prefix) - 1);
14
+ const { start, end } = labelWindow(labels, activeIndex, budget, separator);
15
+ const parts: string[] = [];
16
+ if (start > 0) parts.push(theme.fg('muted', '…'));
17
+ for (let index = start; index <= end; index++) {
18
+ const label = labels[index] ?? '';
19
+ parts.push(index === activeIndex ? theme.fg('accent', theme.bold(label)) : theme.fg('muted', label));
20
+ }
21
+ if (end < labels.length - 1) parts.push(theme.fg('muted', '…'));
22
+ let strip = parts.join(border(separator));
23
+ let body: string;
24
+ if (visibleWidth(strip) > budget) {
25
+ const active = truncateToWidth(labels[activeIndex] ?? '', inner, '');
26
+ strip = theme.fg('accent', theme.bold(active));
27
+ body = strip;
28
+ } else {
29
+ body = border(prefix) + strip + border(' ');
30
+ }
31
+ body += border('─'.repeat(Math.max(0, inner - visibleWidth(body))));
32
+ return bordered ? border('╭') + body + border('╮') : body;
33
+ }
@@ -0,0 +1,105 @@
1
+ import type { Theme } from '@earendil-works/pi-coding-agent';
2
+ import { type Component, type Focusable, matchesKey, type TUI } from '@earendil-works/pi-tui';
3
+ import type { ModalDialog } from './modal-dialog';
4
+ import { renderSectionRule } from './section-strip';
5
+ import { padLine } from './text';
6
+
7
+ export type SectionFrame = 'inline' | 'bordered';
8
+
9
+ export interface ModalSection<TResult> {
10
+ label: string;
11
+ dialog: ModalDialog<TResult>;
12
+ onActivate?: () => void;
13
+ }
14
+
15
+ /** Frame and section routing around retained, caller-wired embedded dialogs. */
16
+ export class SectionedModal<TResult> implements Component, Focusable {
17
+ private readonly activated = new Set<number>();
18
+ private readonly frame: SectionFrame;
19
+ private activeIndex: number;
20
+ private _focused = false;
21
+
22
+ public constructor(
23
+ private readonly tui: TUI,
24
+ private readonly theme: Theme,
25
+ private readonly options: { sections: ModalSection<TResult>[]; frame?: SectionFrame; initialSectionIndex?: number },
26
+ ) {
27
+ if (options.sections.length === 0) throw new Error('SectionedModal requires at least one section');
28
+ this.frame = options.frame ?? 'inline';
29
+ this.activeIndex = Math.min(Math.max(0, options.initialSectionIndex ?? 0), options.sections.length - 1);
30
+ for (const section of options.sections) {
31
+ section.dialog.focused = false;
32
+ if (options.sections.length > 1) section.dialog.setExtraHints([['^]/^[', 'Section']]);
33
+ }
34
+ this.activate();
35
+ }
36
+
37
+ public get activeSectionIndex(): number {
38
+ return this.activeIndex;
39
+ }
40
+
41
+ public get focused(): boolean {
42
+ return this._focused;
43
+ }
44
+
45
+ public set focused(value: boolean) {
46
+ this._focused = value;
47
+ for (const [index, section] of this.options.sections.entries()) section.dialog.focused = value && index === this.activeIndex;
48
+ }
49
+
50
+ public handleInput(data: string): void {
51
+ if (matchesKey(data, 'ctrl+]')) {
52
+ this.switchSection(1);
53
+ } else if (data !== '\x1b' && matchesKey(data, 'ctrl+[')) {
54
+ this.switchSection(-1);
55
+ } else {
56
+ this.activeDialog().handleInput(data);
57
+ }
58
+ }
59
+
60
+ public render(width: number): string[] {
61
+ const safeWidth = Math.max(3, width);
62
+ const bordered = this.frame === 'bordered';
63
+ const inner = safeWidth - (bordered ? 2 : 0);
64
+ const lines = this.activeDialog().render(inner);
65
+ const border = (text: string) => this.theme.fg('border', text);
66
+ const top = renderSectionRule(
67
+ this.theme,
68
+ this.options.sections.map(section => section.label),
69
+ this.activeIndex,
70
+ safeWidth,
71
+ this.frame,
72
+ );
73
+ if (bordered) {
74
+ const side = border('│');
75
+ return [top, ...lines.map(line => `${side}${padLine(line, inner)}${side}`), border(`╰${'─'.repeat(inner)}╯`)];
76
+ }
77
+ return [top, ...lines, border('─'.repeat(safeWidth))];
78
+ }
79
+
80
+ public invalidate(): void {
81
+ for (const section of this.options.sections) section.dialog.invalidate();
82
+ }
83
+
84
+ private activeDialog(): ModalDialog<TResult> {
85
+ const section = this.options.sections[this.activeIndex];
86
+ if (section === undefined) throw new Error('SectionedModal requires at least one section');
87
+ return section.dialog;
88
+ }
89
+
90
+ private switchSection(direction: -1 | 1): void {
91
+ const count = this.options.sections.length;
92
+ if (count === 1) return;
93
+ this.activeDialog().resetNavigation();
94
+ this.activeIndex = (this.activeIndex + direction + count) % count;
95
+ this.focused = this._focused;
96
+ this.activate();
97
+ this.tui.requestRender();
98
+ }
99
+
100
+ private activate(): void {
101
+ if (this.activated.has(this.activeIndex)) return;
102
+ this.activated.add(this.activeIndex);
103
+ this.options.sections[this.activeIndex]?.onActivate?.();
104
+ }
105
+ }
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import type { Theme } from '@earendil-works/pi-coding-agent';
7
7
  import { truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
8
+ import { labelWindow } from './label-window';
8
9
  import { singleLine } from './text';
9
10
 
10
11
  const SEPARATOR = ' ';
@@ -18,32 +19,7 @@ export function renderTabStrip(theme: Theme, labels: string[], activeIndex: numb
18
19
  return styleLabels(theme, labels, activeIndex, 0, labels.length - 1, false, false);
19
20
  }
20
21
 
21
- let start = activeIndex;
22
- let end = activeIndex;
23
- let expandLeft = true;
24
- while (true) {
25
- const nextStart = expandLeft && start > 0 ? start - 1 : start;
26
- const nextEnd = !expandLeft && end < labels.length - 1 ? end + 1 : end;
27
- expandLeft = !expandLeft;
28
-
29
- if (nextStart === start && nextEnd === end) {
30
- if ((start === 0 || nextStart === start) && (end === labels.length - 1 || nextEnd === end)) break;
31
- continue;
32
- }
33
-
34
- const candidate = plainViewport(labels, nextStart, nextEnd);
35
- if (visibleWidth(candidate) <= safeWidth) {
36
- start = nextStart;
37
- end = nextEnd;
38
- continue;
39
- }
40
-
41
- const otherStart = start > 0 ? start - 1 : start;
42
- const otherEnd = end < labels.length - 1 ? end + 1 : end;
43
- if ((otherStart === start && otherEnd === end) || visibleWidth(plainViewport(labels, otherStart, otherEnd)) > safeWidth) break;
44
- start = otherStart;
45
- end = otherEnd;
46
- }
22
+ const { start, end } = labelWindow(labels, activeIndex, safeWidth, SEPARATOR);
47
23
 
48
24
  const leftOmitted = start > 0;
49
25
  const rightOmitted = end < labels.length - 1;