@0xkahi/pi-qol 1.4.0 → 1.4.2
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.
- package/README.md +11 -2
- package/assets/config.schema.json +5 -0
- package/package.json +6 -6
- package/src/extensions/context-view/capture.ts +74 -35
- package/src/extensions/context-view/codemap.md +24 -16
- package/src/extensions/context-view/constants.ts +3 -0
- package/src/extensions/context-view/context-view-controller.ts +47 -13
- package/src/extensions/context-view/index.ts +25 -9
- package/src/extensions/context-view/measure.ts +2 -1
- package/src/extensions/context-view/model.ts +44 -3
- package/src/extensions/context-view/presentation.ts +6 -0
- package/src/extensions/context-view/prompt-additions.ts +5 -3
- package/src/extensions/context-view/ui/codemap.md +60 -93
- package/src/extensions/context-view/ui/context-view-dialog.ts +14 -7
- package/src/extensions/context-view/ui/copy.ts +42 -0
- package/src/extensions/context-view/ui/highlight.ts +91 -0
- package/src/extensions/context-view/ui/injections-model.ts +52 -0
- package/src/extensions/context-view/ui/injections-view.ts +124 -27
- package/src/extensions/context-view/ui/search.ts +28 -0
- package/src/extensions/context-view/ui/searchable-preview.ts +175 -0
- package/src/extensions/context-view/ui/usage-block-layer.ts +18 -7
- package/src/extensions/context-view/ui/usage-view.ts +57 -24
- package/src/libs/modal/README.md +9 -3
- package/src/libs/modal/codemap.md +5 -5
- package/src/libs/modal/index.ts +1 -1
- package/src/libs/modal/modal-dialog.ts +44 -3
- package/src/libs/modal/preview-layer.ts +3 -3
- package/src/libs/modal/types.ts +11 -0
- package/src/schemas/context-view.config.schema.ts +2 -0
- package/src/extensions/context-view/ui/wheel-preview-layer.ts +0 -104
- package/src/extensions/context-view/ui/wheel.ts +0 -66
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* shared modal library; this tab owns only its content.
|
|
8
8
|
*/
|
|
9
9
|
import type { Theme, ThemeColor } from '@earendil-works/pi-coding-agent';
|
|
10
|
-
import { matchesKey, visibleWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
|
|
10
|
+
import { matchesKey, type TuiMouseEvent, type TuiMouseEventResult, visibleWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
|
|
11
11
|
|
|
12
12
|
import {
|
|
13
13
|
BODY_INDENT,
|
|
@@ -24,14 +24,14 @@ import {
|
|
|
24
24
|
} from '../../../libs/modal';
|
|
25
25
|
import type { ContextUsageSnapshot, JsonSpan, UsageCategory, UsagePreviewEntry } from '../model';
|
|
26
26
|
import { collectPreviewEntries } from '../usage';
|
|
27
|
+
import { type CopyServices, copyWithNotice } from './copy';
|
|
27
28
|
import { normalizeInlineText, normalizePreviewText } from './injections-model';
|
|
28
29
|
import { expandJsonSpan } from './json-preview';
|
|
30
|
+
import { SearchablePreview } from './searchable-preview';
|
|
29
31
|
import { previewBodyLines, previewLegendLines } from './section-preview';
|
|
30
32
|
import { splitSkillPreview } from './skill-preview';
|
|
31
33
|
import { UsageBlockLayer } from './usage-block-layer';
|
|
32
34
|
import { buildUsageMap, calculateFitMapScale, DEFAULT_MAP_COLUMNS, DEFAULT_MAP_ROWS, type UsageMapCell } from './usage-map';
|
|
33
|
-
import { DEFAULT_WHEEL_SCROLL_LINES, parseWheelDirection } from './wheel';
|
|
34
|
-
import { WheelPreviewLayer } from './wheel-preview-layer';
|
|
35
35
|
|
|
36
36
|
const USAGE_DESCRIPTION =
|
|
37
37
|
'Estimated context for the next model request. ' + "Token counts are approximate and may differ from the provider's estimate.";
|
|
@@ -55,7 +55,7 @@ const COMPACTED_CELL = '▦';
|
|
|
55
55
|
const BUFFER_CELL = '⛝';
|
|
56
56
|
const FREE_CELL = '⛶';
|
|
57
57
|
const BREAKDOWN_MARKER = '•';
|
|
58
|
-
/** Title and its trailing blank row the full-content
|
|
58
|
+
/** Title and its trailing blank row the full-content layer spends outside its body. */
|
|
59
59
|
const FULL_CONTENT_FIXED_LINE_COUNT = 2;
|
|
60
60
|
|
|
61
61
|
/** Everything the Usage view renders, classified once when the view opens. */
|
|
@@ -98,16 +98,19 @@ export class UsageView implements ModalTab {
|
|
|
98
98
|
private readonly navigator: ListNavigator;
|
|
99
99
|
private readonly cache = new RenderCache();
|
|
100
100
|
private readonly fitMapScale: number | undefined;
|
|
101
|
-
private
|
|
101
|
+
private percentBasis: 'window' | 'used' = 'window';
|
|
102
102
|
private context: ModalTabContext | undefined;
|
|
103
103
|
private mapScale: UsageMapScale = 'window';
|
|
104
104
|
private currentWidth: number | undefined;
|
|
105
105
|
|
|
106
106
|
/** Create a view over one precomputed usage snapshot. */
|
|
107
|
-
public constructor(
|
|
107
|
+
public constructor(
|
|
108
|
+
theme: Theme,
|
|
109
|
+
input: UsageViewInput,
|
|
110
|
+
private readonly copy: CopyServices = { notices: { showNotice: () => undefined } },
|
|
111
|
+
) {
|
|
108
112
|
this.theme = theme;
|
|
109
113
|
this.usage = input.usage;
|
|
110
|
-
this.wheelScrollLines = wheelScrollLines;
|
|
111
114
|
this.legendRows = this.buildLegendRows();
|
|
112
115
|
const selectableCount = this.legendRows.filter(row => row.type === 'category').length;
|
|
113
116
|
this.navigator = new ListNavigator(this.legendRows.length, 1, selectableCount);
|
|
@@ -123,19 +126,42 @@ export class UsageView implements ModalTab {
|
|
|
123
126
|
}
|
|
124
127
|
|
|
125
128
|
public hints(): Hint[] {
|
|
126
|
-
const hints: Hint[] = [
|
|
129
|
+
const hints: Hint[] = [
|
|
130
|
+
['Enter', 'Preview'],
|
|
131
|
+
['y', 'Copy'],
|
|
132
|
+
];
|
|
133
|
+
if (this.canTogglePercentBasis()) hints.push(['p', 'Percent basis']);
|
|
127
134
|
if (this.canToggleMapScale(this.currentWidth)) hints.push(['Z', 'Zoom']);
|
|
128
135
|
return hints;
|
|
129
136
|
}
|
|
130
137
|
|
|
131
|
-
/** Handle
|
|
138
|
+
/** Handle view-local zoom, percentage basis, and copy bindings. */
|
|
132
139
|
public handleInput(data: string): void {
|
|
133
|
-
const wheel = parseWheelDirection(data);
|
|
134
|
-
if (wheel !== undefined) {
|
|
135
|
-
if (this.navigator.moveBy(wheel)) this.cache.clear();
|
|
136
|
-
return;
|
|
137
|
-
}
|
|
138
140
|
if (matchesKey(data, 'z')) this.toggleMapScale();
|
|
141
|
+
if (matchesKey(data, 'p') && this.canTogglePercentBasis()) {
|
|
142
|
+
this.percentBasis = this.percentBasis === 'window' ? 'used' : 'window';
|
|
143
|
+
this.cache.clear();
|
|
144
|
+
}
|
|
145
|
+
if (matchesKey(data, 'y')) {
|
|
146
|
+
const row = this.legendRows[this.navigator.selected];
|
|
147
|
+
const text =
|
|
148
|
+
row?.type === 'category'
|
|
149
|
+
? collectPreviewEntries(row.category)
|
|
150
|
+
.map(entry => entry.text)
|
|
151
|
+
.join('\n\n')
|
|
152
|
+
: '';
|
|
153
|
+
void copyWithNotice(this.copy, text);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
public handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
|
|
158
|
+
if (event.type !== 'wheel') return undefined;
|
|
159
|
+
if (this.navigator.moveBy(event.wheelDelta ?? 0)) this.cache.clear();
|
|
160
|
+
return { handled: true };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
private canTogglePercentBasis(): boolean {
|
|
164
|
+
return (this.usage.reported?.contextWindow ?? 0) > 0 || this.usage.estimatedTokens > 0;
|
|
139
165
|
}
|
|
140
166
|
|
|
141
167
|
/** Apply semantic movement in the category list, or open a preview layer. */
|
|
@@ -277,7 +303,7 @@ export class UsageView implements ModalTab {
|
|
|
277
303
|
const viewport = calculateViewport(this.legendRows.length, rows, headerLineCount);
|
|
278
304
|
this.navigator.setVisibleCount(viewport.visibleCount);
|
|
279
305
|
|
|
280
|
-
const heading = theme.fg('mdHeading', theme.bold(
|
|
306
|
+
const heading = theme.fg('mdHeading', theme.bold(`Category (% of ${this.percentBasis}):`));
|
|
281
307
|
const rowWidth = Math.max(1, width - CURSOR_COLUMN_WIDTH);
|
|
282
308
|
const columns = this.legendColumns(rowWidth);
|
|
283
309
|
const visibleRows: string[] = [];
|
|
@@ -314,8 +340,8 @@ export class UsageView implements ModalTab {
|
|
|
314
340
|
if (reported === undefined) return this.theme.fg('muted', 'Context usage unavailable.');
|
|
315
341
|
const contextWindow = formatTokens(reported.contextWindow);
|
|
316
342
|
if (reported.tokens === undefined) {
|
|
317
|
-
const percent = formatPercent(this.usage.estimatedTokens / reported.contextWindow);
|
|
318
|
-
return this.theme.fg('text', `≈${formatTokens(this.usage.estimatedTokens)}/${contextWindow}
|
|
343
|
+
const percent = reported.contextWindow > 0 ? ` (${formatPercent(this.usage.estimatedTokens / reported.contextWindow)})` : '';
|
|
344
|
+
return this.theme.fg('text', `≈${formatTokens(this.usage.estimatedTokens)}/${contextWindow}${percent}`);
|
|
319
345
|
}
|
|
320
346
|
const percent = reported.percent === undefined ? '' : ` (${formatPercent(reported.percent / 100)})`;
|
|
321
347
|
return this.theme.fg('text', `${formatTokens(reported.tokens)}/${contextWindow}${percent}`);
|
|
@@ -354,7 +380,7 @@ export class UsageView implements ModalTab {
|
|
|
354
380
|
const rows = this.legendRows;
|
|
355
381
|
const labelWidth = Math.max(1, ...rows.map(row => this.plainLegendLabel(row).length));
|
|
356
382
|
const tokenWidth = Math.max(1, ...rows.map(row => formatTokens(legendTokens(row)).length));
|
|
357
|
-
const percentWidth = Math.max(0, ...rows.map(row => this.
|
|
383
|
+
const percentWidth = Math.max(0, ...rows.map(row => this.legendPercent(row).length));
|
|
358
384
|
const rightWidth = tokenWidth + (percentWidth > 0 ? LEGEND_VALUE_GAP + percentWidth : 0);
|
|
359
385
|
const idealValue = Math.min(MAX_LEGEND_VALUE_COLUMN, labelWidth + LEGEND_LEADER_GAP);
|
|
360
386
|
return {
|
|
@@ -371,7 +397,7 @@ export class UsageView implements ModalTab {
|
|
|
371
397
|
const tokens = formatTokens(legendTokens(row));
|
|
372
398
|
const valueColor = selected ? 'accent' : row.type === 'category' && row.depth > 1 ? 'dim' : 'muted';
|
|
373
399
|
const tokenPadding = ' '.repeat(Math.max(0, columns.tokenWidth - tokens.length));
|
|
374
|
-
const percent = this.
|
|
400
|
+
const percent = this.legendPercent(row);
|
|
375
401
|
const percentPart = percent === '' ? '' : `${' '.repeat(LEGEND_VALUE_GAP)}${this.theme.fg(selected ? 'accent' : 'dim', percent)}`;
|
|
376
402
|
return fitLine(`${left}${leader}${this.theme.fg(valueColor, tokens)}${tokenPadding}${percentPart}`, width);
|
|
377
403
|
}
|
|
@@ -406,10 +432,15 @@ export class UsageView implements ModalTab {
|
|
|
406
432
|
}
|
|
407
433
|
|
|
408
434
|
/** Percentage text used by the independently aligned rightmost column. */
|
|
435
|
+
private legendPercent(row: LegendRow): string {
|
|
436
|
+
if (this.percentBasis === 'used' && row.type !== 'category') return '';
|
|
437
|
+
return this.plainLegendPercent(legendTokens(row));
|
|
438
|
+
}
|
|
439
|
+
|
|
409
440
|
private plainLegendPercent(tokens: number): string {
|
|
410
|
-
const
|
|
411
|
-
if (
|
|
412
|
-
return formatPercent(tokens /
|
|
441
|
+
const denominator = this.percentBasis === 'window' ? this.usage.reported?.contextWindow : this.usage.estimatedTokens;
|
|
442
|
+
if (denominator === undefined || denominator <= 0) return '';
|
|
443
|
+
return formatPercent(tokens / denominator);
|
|
413
444
|
}
|
|
414
445
|
|
|
415
446
|
/** Colored occupied/partial/buffer/free glyph for one map cell. */
|
|
@@ -434,6 +465,7 @@ export class UsageView implements ModalTab {
|
|
|
434
465
|
title: () => this.theme.fg('accent', this.theme.bold(normalizeInlineText(row.category.label))),
|
|
435
466
|
meta: () => this.theme.fg('muted', `${formatTokens(row.category.tokens)}${percent === '' ? '' : ` · ${percent}`}`),
|
|
436
467
|
entries,
|
|
468
|
+
copy: this.copy,
|
|
437
469
|
entryHeader: entry => this.entryHeader(entry),
|
|
438
470
|
entryBody: (entry, width) => this.entryContentLines(entry, Math.max(10, width - BODY_INDENT.length * 2 - 1), compactSkills),
|
|
439
471
|
description: (width, height) => this.previewDescriptionLines(width, height, row, entries),
|
|
@@ -446,13 +478,14 @@ export class UsageView implements ModalTab {
|
|
|
446
478
|
private openFullContent(row: CategoryLegendRow, entry: UsagePreviewEntry, compactSkills: boolean): void {
|
|
447
479
|
const breadcrumb = entry.breadcrumb.map(normalizeInlineText).filter(Boolean).join(' / ');
|
|
448
480
|
this.context?.pushLayer(
|
|
449
|
-
new
|
|
481
|
+
new SearchablePreview(this.theme, {
|
|
450
482
|
title: () => this.theme.fg('accent', this.theme.bold(breadcrumb || normalizeInlineText(row.category.label))),
|
|
451
483
|
meta: () => this.theme.fg('muted', formatTokens(entry.tokens)),
|
|
452
484
|
// Match the block stream's two-column selection gutter so its hidden-line count stays exact.
|
|
453
485
|
body: width => this.entryContentLines(entry, Math.max(10, width - BODY_INDENT.length * 2 - 3), compactSkills),
|
|
454
486
|
description: (width, height) => this.fullContentLegendLines(width, height, entry, compactSkills),
|
|
455
|
-
|
|
487
|
+
copy: this.copy,
|
|
488
|
+
copyText: () => entry.text,
|
|
456
489
|
}),
|
|
457
490
|
);
|
|
458
491
|
}
|
package/src/libs/modal/README.md
CHANGED
|
@@ -55,6 +55,7 @@ That's the whole job. The shell gives you: Esc-to-cancel, `↑↓`/PgUp/PgDn via
|
|
|
55
55
|
└──────────────────────────────────────────────┘
|
|
56
56
|
|
|
57
57
|
Input routing (first match wins):
|
|
58
|
+
0. capturesInput() is true → raw key to top layer, else active tab
|
|
58
59
|
1. Tab / Shift+Tab → cycle tabs (wraps; scheme resets)
|
|
59
60
|
2. navigation scheme → semantic action:
|
|
60
61
|
dismiss → pop active tab's top layer, else cancel dialog
|
|
@@ -215,11 +216,14 @@ await presentModal(ctx.ui, layout, (tui, theme, keybindings, done, frame) =>
|
|
|
215
216
|
|
|
216
217
|
## Behavior contract (what users can rely on)
|
|
217
218
|
|
|
219
|
+
- **Input capture** — tabs and layers may implement `capturesInput?(): boolean`. While true, all raw keys (including Tab, j, q and Esc) go directly to that target's `handleInput`, before tab cycling or scheme mapping. Only its own `hints()` appear in the footer; it owns confirmation/cancellation and releasing capture.
|
|
220
|
+
- **Mouse** — optional `handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined` receives pi-tui normalized events on the top layer, otherwise the active tab. The shell returns the result unchanged; a layer without a handler does not fall through to its tab. Wheel consumers use the host's `wheelDelta` without rescaling and return `{ handled: true }`.
|
|
221
|
+
- **Transient notices** — `dialog.showNotice(text, tone, ttlMs)` replaces the footer hint line without adding height. `ModalNoticeTone` is `'success' | 'warning' | 'error'`. The newest notice wins; expiry restores hints and requests a render. These are independent of the persistent `notices` option above the content.
|
|
218
222
|
- **Esc/q** closes the top preview layer first, then the dialog (`onComplete(cancelValue)`).
|
|
219
|
-
- **Tab / Shift+Tab** cycles tabs even while a preview is open; every tab keeps its selection, scroll, zoom, and open layers.
|
|
223
|
+
- **Tab / Shift+Tab** cycles tabs unless the active target captures input, even while a preview is open; every tab keeps its selection, scroll, zoom, and open layers.
|
|
220
224
|
- **Tab labels are live** — return counts from a closure and the strip updates on the next render.
|
|
221
225
|
- **`gg` chords never leak** across tab switches or layer push/pop (shell calls `scheme.reset()`).
|
|
222
|
-
- **
|
|
226
|
+
- **Shared filter + Vim don't mix** — the shell-level `filter` is for picker schemes. A view-owned temporary filter/search prompt can use `capturesInput()` with Vim navigation, releasing capture when editing ends.
|
|
223
227
|
- **Height 'half'** bounds the whole dialog to `floor(terminal.rows / 2)` lines including frame; tabs must render exactly the `height` they're given.
|
|
224
228
|
|
|
225
229
|
## API reference
|
|
@@ -244,7 +248,9 @@ await presentModal(ctx.ui, layout, (tui, theme, keybindings, done, frame) =>
|
|
|
244
248
|
|
|
245
249
|
`extraHints?: Hint[] | (() => Hint[])` inserts footer hints before Esc.
|
|
246
250
|
|
|
247
|
-
|
|
251
|
+
`PreviewLayer` exposes protected `scroller`, `theme`, and `options` for specialized subclasses; its default keyboard-only scrolling behavior is unchanged. Subclasses or wrappers can implement input capture and normalized mouse handling.
|
|
252
|
+
|
|
253
|
+
Methods: `showNotice(text, tone, ttlMs)`, `handleMouse(event)`, `complete(result)`, `setExtraHints(hints)`, `resetNavigation()`, `handleInput(data)`, `render(width)`, `invalidate()`, `focused`, `activeTab`, `activeIndex`.
|
|
248
254
|
|
|
249
255
|
### `ListTab<T>` options
|
|
250
256
|
|
|
@@ -8,13 +8,13 @@ The library is self-contained: it imports only from Pi host packages (`@earendil
|
|
|
8
8
|
|
|
9
9
|
## Module Roles
|
|
10
10
|
|
|
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 | `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.
|
|
11
|
+
- `types.ts` — Contracts: `NavigationAction`/`NavigationResult`/`NavigationScheme` (pure key→action mappers), `ModalTab` (content strategy), `ModalLayer`, `ModalTabContext` (`pushLayer`), `Hint`, and notice tones. Tabs/layers may implement `capturesInput()` and `handleMouse(event)`.
|
|
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: raw input to the top layer (otherwise active tab) when `capturesInput()` is true, before 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. While input is captured, the target's own hints replace normal navigation hints. `handleMouse` forwards normalized Pi mouse events to the same target's optional handler, returning its result or `undefined`; it does not parse mouse escape sequences. `showNotice(text, tone, ttlMs)` temporarily replaces the footer hint line without changing height; a generation counter and expiry render request ensure only the latest notice survives.
|
|
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
|
-
- `preview-layer.ts` — `PreviewLayer`: title + right-aligned meta header, `PreviewScroller`-windowed body, overflow counter, optional pinned description; dismissal is shell-owned (pops the layer).
|
|
17
|
+
- `preview-layer.ts` — `PreviewLayer`: optional normalized wheel handling via `handleMouse`/`wheelDelta`, 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
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+L/disambiguated Ctrl+H (raw `0x08` stays Backspace) 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
20
|
- `section-strip.ts` — `renderSectionRule` draws active/inactive section labels in the top rule or rounded border, adding no height.
|
|
@@ -28,11 +28,11 @@ The library is self-contained: it imports only from Pi host packages (`@earendil
|
|
|
28
28
|
|
|
29
29
|
1. An extension builds `ModalTab`s (commonly `ListTab`, or custom tabs using `ListNavigator`/`PreviewLayer`/`RenderCache`) and calls `presentModal` with a semantic layout. The presenter supplies the resolved frame and host mounting options while the extension constructs `ModalDialog` with its own height/scheme/filter options plus `cancelValue`/`onComplete`.
|
|
30
30
|
2. The shell attaches a `ModalTabContext` to each tab (for `pushLayer`) and applies any initial filter query.
|
|
31
|
-
3. The host (`ctx.ui.custom`) drives `render(width)` and `
|
|
31
|
+
3. The host (`ctx.ui.custom`) drives `render(width)`, `handleInput(data)`, and normalized `handleMouse(event)`; the shell routes input per the order above and calls `tui.requestRender()` after input.
|
|
32
32
|
4. Confirm flows: scheme `confirm` → tab `handleNavigation` → tab's confirm callback → `dialog.complete(value)`. Dismissal pops the active tab's top layer first, then completes with the cancel value.
|
|
33
33
|
|
|
34
34
|
## Integration Points
|
|
35
35
|
|
|
36
|
-
- **Consumers**: `src/extensions/model-select/model-select-dialog.ts` (three `ListTab` sections, filter slot, both frame styles, wrap selection) and `src/extensions/context-view/ui/context-view-dialog.ts` (Vim scheme, half-height, notices; custom `UsageView`/`InjectionsView` tabs with
|
|
36
|
+
- **Consumers**: `src/extensions/model-select/model-select-dialog.ts` (three `ListTab` sections, filter slot, both frame styles, wrap selection) and `src/extensions/context-view/ui/context-view-dialog.ts` (Vim scheme, half-height, notices; custom `UsageView`/`InjectionsView` tabs with input-capturing filter/search targets and copy-result footer notices).
|
|
37
37
|
- **Host packages**: `pi-tui` (`Component`, `Focusable`, `Input`, `Key`, `matchesKey`, `fuzzyFilter`, width helpers), `pi-coding-agent` types (`ExtensionUIContext`, `Theme`, `KeybindingsManager`).
|
|
38
38
|
- **Tests**: `test/modal/` (schemes, shell behavior, self-containment audit).
|
package/src/libs/modal/index.ts
CHANGED
|
@@ -29,4 +29,4 @@ export {
|
|
|
29
29
|
type Viewport,
|
|
30
30
|
wrapDescriptionLines,
|
|
31
31
|
} from './text';
|
|
32
|
-
export type { Hint, ModalLayer, ModalTab, ModalTabContext, NavigationAction, NavigationResult, NavigationScheme } from './types';
|
|
32
|
+
export type { Hint, ModalLayer, ModalNoticeTone, ModalTab, ModalTabContext, NavigationAction, NavigationResult, NavigationScheme } from './types';
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* implement content. See `types.ts` for the tab/layer/scheme contracts.
|
|
6
6
|
*
|
|
7
7
|
* Input routing order:
|
|
8
|
+
* 0. A capturing content target receives raw input directly.
|
|
8
9
|
* 1. Tab/Shift+Tab cycles tabs (wrapping, scheme reset).
|
|
9
10
|
* 2. The navigation scheme maps a key to a semantic action; `dismiss` pops
|
|
10
11
|
* the active tab's top layer, or completes the dialog with the cancel
|
|
@@ -14,11 +15,20 @@
|
|
|
14
15
|
* the active tab.
|
|
15
16
|
*/
|
|
16
17
|
import type { KeybindingsManager, Theme } from '@earendil-works/pi-coding-agent';
|
|
17
|
-
import {
|
|
18
|
+
import {
|
|
19
|
+
type Component,
|
|
20
|
+
type Focusable,
|
|
21
|
+
Input,
|
|
22
|
+
Key,
|
|
23
|
+
matchesKey,
|
|
24
|
+
type TUI,
|
|
25
|
+
type TuiMouseEvent,
|
|
26
|
+
type TuiMouseEventResult,
|
|
27
|
+
} from '@earendil-works/pi-tui';
|
|
18
28
|
import { PiKeybindingsScheme } from './navigation/pi-scheme';
|
|
19
29
|
import { renderTabStrip } from './tab-strip';
|
|
20
30
|
import { fitToTerminalHeight, hintRow, normalizeTerminalRows, padLine, singleLine } from './text';
|
|
21
|
-
import type { Hint, ModalLayer, ModalTab, NavigationScheme } from './types';
|
|
31
|
+
import type { Hint, ModalLayer, ModalNoticeTone, ModalTab, NavigationScheme } from './types';
|
|
22
32
|
|
|
23
33
|
/** Framing style: inline rules, or a rounded border for host-centered overlays. */
|
|
24
34
|
export type ModalFrame = 'inline' | 'bordered' | 'none';
|
|
@@ -61,6 +71,9 @@ export class ModalDialog<TResult> implements Component, Focusable {
|
|
|
61
71
|
private readonly layerStacks = new Map<ModalTab, ModalLayer[]>();
|
|
62
72
|
private activeTabIndex: number;
|
|
63
73
|
private _focused = false;
|
|
74
|
+
private notice: { text: string; tone: ModalNoticeTone } | undefined;
|
|
75
|
+
private noticeGeneration = 0;
|
|
76
|
+
private noticeTimer: ReturnType<typeof setTimeout> | undefined;
|
|
64
77
|
private extraHints: Hint[] | (() => Hint[]);
|
|
65
78
|
|
|
66
79
|
public constructor(
|
|
@@ -130,7 +143,33 @@ export class ModalDialog<TResult> implements Component, Focusable {
|
|
|
130
143
|
this.scheme.reset();
|
|
131
144
|
}
|
|
132
145
|
|
|
146
|
+
/** Replace the footer hints temporarily without changing the dialog height. */
|
|
147
|
+
public showNotice(text: string, tone: ModalNoticeTone, ttlMs: number): void {
|
|
148
|
+
const generation = ++this.noticeGeneration;
|
|
149
|
+
clearTimeout(this.noticeTimer);
|
|
150
|
+
this.notice = { text, tone };
|
|
151
|
+
this.noticeTimer = setTimeout(() => {
|
|
152
|
+
if (generation !== this.noticeGeneration) return;
|
|
153
|
+
this.notice = undefined;
|
|
154
|
+
this.noticeTimer = undefined;
|
|
155
|
+
this.tui.requestRender();
|
|
156
|
+
}, ttlMs);
|
|
157
|
+
this.noticeTimer.unref?.();
|
|
158
|
+
this.tui.requestRender();
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
public handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
|
|
162
|
+
return this.content().handleMouse?.(event);
|
|
163
|
+
}
|
|
164
|
+
|
|
133
165
|
public handleInput(data: string): void {
|
|
166
|
+
const target = this.content();
|
|
167
|
+
if (target.capturesInput?.()) {
|
|
168
|
+
this.scheme.reset();
|
|
169
|
+
target.handleInput(data);
|
|
170
|
+
this.tui.requestRender();
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
134
173
|
if (this.options.tabs.length > 1) {
|
|
135
174
|
if (matchesKey(data, Key.shift('tab'))) {
|
|
136
175
|
this.switchTab(-1);
|
|
@@ -266,7 +305,8 @@ export class ModalDialog<TResult> implements Component, Focusable {
|
|
|
266
305
|
}
|
|
267
306
|
lines.push(...content, '');
|
|
268
307
|
|
|
269
|
-
|
|
308
|
+
const footer = this.notice === undefined ? hintRow(this.theme, this.footerHints()) : this.theme.fg(this.notice.tone, this.notice.text);
|
|
309
|
+
lines.push(singleLine(footer, width));
|
|
270
310
|
return lines;
|
|
271
311
|
}
|
|
272
312
|
|
|
@@ -302,6 +342,7 @@ export class ModalDialog<TResult> implements Component, Focusable {
|
|
|
302
342
|
private footerHints(): Hint[] {
|
|
303
343
|
const layer = this.topLayer();
|
|
304
344
|
const target = layer ?? this.activeTab;
|
|
345
|
+
if (target.capturesInput?.()) return target.hints();
|
|
305
346
|
const hints: Hint[] = [...this.scheme.hints(layer === undefined ? 'Navigate' : 'Scroll'), ...target.hints()];
|
|
306
347
|
if (this.options.tabs.length > 1) hints.push(['Tab', 'Switch']);
|
|
307
348
|
hints.push(...(typeof this.extraHints === 'function' ? this.extraHints() : this.extraHints));
|
|
@@ -23,11 +23,11 @@ export interface PreviewLayerOptions {
|
|
|
23
23
|
}
|
|
24
24
|
|
|
25
25
|
export class PreviewLayer implements ModalLayer {
|
|
26
|
-
|
|
26
|
+
protected readonly scroller = new PreviewScroller();
|
|
27
27
|
|
|
28
28
|
public constructor(
|
|
29
|
-
|
|
30
|
-
|
|
29
|
+
protected readonly theme: Theme,
|
|
30
|
+
protected readonly options: PreviewLayerOptions,
|
|
31
31
|
) {}
|
|
32
32
|
|
|
33
33
|
public hints(): Hint[] {
|
package/src/libs/modal/types.ts
CHANGED
|
@@ -5,6 +5,11 @@
|
|
|
5
5
|
* directory can be copied unchanged into other Pi plugin projects.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
+
import type { TuiMouseEvent, TuiMouseEventResult } from '@earendil-works/pi-tui';
|
|
9
|
+
|
|
10
|
+
/** Tone for a transient footer notice. */
|
|
11
|
+
export type ModalNoticeTone = 'success' | 'warning' | 'error';
|
|
12
|
+
|
|
8
13
|
/** Semantic action produced by a navigation scheme for one key press. */
|
|
9
14
|
export type NavigationAction = 'step-back' | 'step-forward' | 'page-back' | 'page-forward' | 'first' | 'last' | 'confirm' | 'dismiss';
|
|
10
15
|
|
|
@@ -31,6 +36,9 @@ export interface NavigationScheme {
|
|
|
31
36
|
export interface ModalLayer {
|
|
32
37
|
render(width: number, height: number | undefined): string[];
|
|
33
38
|
handleInput(data: string): void;
|
|
39
|
+
/** Own raw keyboard input before tab cycling and navigation mapping. */
|
|
40
|
+
capturesInput?(): boolean;
|
|
41
|
+
handleMouse?(event: TuiMouseEvent): TuiMouseEventResult | undefined;
|
|
34
42
|
handleNavigation(action: NavigationAction): void;
|
|
35
43
|
hints(): Hint[];
|
|
36
44
|
invalidate?(): void;
|
|
@@ -56,6 +64,9 @@ export interface ModalTab {
|
|
|
56
64
|
render(width: number, height: number | undefined): string[];
|
|
57
65
|
/** Raw keys the navigation scheme did not handle. */
|
|
58
66
|
handleInput(data: string): void;
|
|
67
|
+
/** Own raw keyboard input before tab cycling and navigation mapping. */
|
|
68
|
+
capturesInput?(): boolean;
|
|
69
|
+
handleMouse?(event: TuiMouseEvent): TuiMouseEventResult | undefined;
|
|
59
70
|
/** Semantic navigation; never includes `dismiss`. */
|
|
60
71
|
handleNavigation(action: NavigationAction): void;
|
|
61
72
|
/** Re-filter content when the dialog owns a shared filter input. */
|
|
@@ -5,6 +5,7 @@ export type ContextViewLayout = z.infer<typeof ContextViewLayoutSchema>;
|
|
|
5
5
|
|
|
6
6
|
export const ContextViewConfigSchema = z.object({
|
|
7
7
|
enabled: z.boolean().default(false),
|
|
8
|
+
auto_probing: z.boolean().default(true),
|
|
8
9
|
layout: ContextViewLayoutSchema.default('inline'),
|
|
9
10
|
});
|
|
10
11
|
export type ContextViewConfig = z.infer<typeof ContextViewConfigSchema>;
|
|
@@ -13,6 +14,7 @@ export const DEFAULT_CONTEXT_VIEW_CONFIG = ContextViewConfigSchema.parse({});
|
|
|
13
14
|
|
|
14
15
|
export const PartialContextViewConfigSchema = z.object({
|
|
15
16
|
enabled: z.boolean().optional(),
|
|
17
|
+
auto_probing: z.boolean().optional(),
|
|
16
18
|
layout: ContextViewLayoutSchema.optional(),
|
|
17
19
|
});
|
|
18
20
|
export type PartialContextViewConfig = z.infer<typeof PartialContextViewConfigSchema>;
|
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Context View preview layer with mouse-wheel support.
|
|
3
|
-
*
|
|
4
|
-
* The shared modal `PreviewLayer` is scroll-only through semantic navigation
|
|
5
|
-
* actions; the Context View adds opt-in wheel scrolling on top, since pi
|
|
6
|
-
* forwards wheel reports only to a focused overlay and never consumes them
|
|
7
|
-
* itself. This layer mirrors the shared preview frame while stepping its own
|
|
8
|
-
* `PreviewScroller` on a wheel notch.
|
|
9
|
-
*/
|
|
10
|
-
import type { Theme } from '@earendil-works/pi-coding-agent';
|
|
11
|
-
|
|
12
|
-
import {
|
|
13
|
-
BODY_INDENT,
|
|
14
|
-
calculateViewport,
|
|
15
|
-
fitLine,
|
|
16
|
-
type Hint,
|
|
17
|
-
type ModalLayer,
|
|
18
|
-
type NavigationAction,
|
|
19
|
-
PreviewScroller,
|
|
20
|
-
spreadLine,
|
|
21
|
-
} from '../../../libs/modal';
|
|
22
|
-
import { DEFAULT_WHEEL_SCROLL_LINES, parseWheelDirection } from './wheel';
|
|
23
|
-
|
|
24
|
-
export interface WheelPreviewLayerOptions {
|
|
25
|
-
/** Styled title rendered on the left of the header line. */
|
|
26
|
-
title: string | (() => string);
|
|
27
|
-
/** Muted metadata rendered right-aligned beside the title. */
|
|
28
|
-
meta?: string | (() => string);
|
|
29
|
-
/** Body lines for the given width; wrapping is the caller's concern. */
|
|
30
|
-
body: (width: number) => string[];
|
|
31
|
-
/** Optional fixed description lines pinned below the body, given the layer's width and height. */
|
|
32
|
-
description?: (width: number, height: number | undefined) => string[];
|
|
33
|
-
/** Layer-specific hints appended after the navigation scheme's hints. */
|
|
34
|
-
hints?: () => Hint[];
|
|
35
|
-
/** Lines one wheel notch scrolls; defaults to the project fallback. */
|
|
36
|
-
wheelScrollLines?: number;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export class WheelPreviewLayer implements ModalLayer {
|
|
40
|
-
private readonly scroller = new PreviewScroller();
|
|
41
|
-
|
|
42
|
-
public constructor(
|
|
43
|
-
private readonly theme: Theme,
|
|
44
|
-
private readonly options: WheelPreviewLayerOptions,
|
|
45
|
-
) {}
|
|
46
|
-
|
|
47
|
-
public hints(): Hint[] {
|
|
48
|
-
return this.options.hints?.() ?? [];
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/** Scroll one wheel notch; every other raw key is ignored by the preview. */
|
|
52
|
-
public handleInput(data: string): void {
|
|
53
|
-
const wheel = parseWheelDirection(data);
|
|
54
|
-
if (wheel === undefined) return;
|
|
55
|
-
this.scroller.scrollBy(wheel * (this.options.wheelScrollLines ?? DEFAULT_WHEEL_SCROLL_LINES));
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
public handleNavigation(action: NavigationAction): void {
|
|
59
|
-
switch (action) {
|
|
60
|
-
case 'step-back':
|
|
61
|
-
this.scroller.scrollBy(-1);
|
|
62
|
-
break;
|
|
63
|
-
case 'step-forward':
|
|
64
|
-
this.scroller.scrollBy(1);
|
|
65
|
-
break;
|
|
66
|
-
case 'page-back':
|
|
67
|
-
this.scroller.page(-1);
|
|
68
|
-
break;
|
|
69
|
-
case 'page-forward':
|
|
70
|
-
this.scroller.page(1);
|
|
71
|
-
break;
|
|
72
|
-
case 'first':
|
|
73
|
-
this.scroller.scrollTo(0);
|
|
74
|
-
break;
|
|
75
|
-
case 'last':
|
|
76
|
-
this.scroller.scrollTo(this.scroller.maxOffset);
|
|
77
|
-
break;
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
public render(width: number, height: number | undefined): string[] {
|
|
82
|
-
const body = this.options.body(width);
|
|
83
|
-
const description = this.options.description?.(width, height) ?? [];
|
|
84
|
-
// title + blank, plus blank + description when present
|
|
85
|
-
const fixedLineCount = 2 + (description.length > 0 ? description.length + 1 : 0);
|
|
86
|
-
const viewport = calculateViewport(body.length, height ?? body.length + fixedLineCount, fixedLineCount);
|
|
87
|
-
this.scroller.setExtent(body.length, viewport.visibleCount);
|
|
88
|
-
|
|
89
|
-
const title = typeof this.options.title === 'function' ? this.options.title() : this.options.title;
|
|
90
|
-
const metaOption = this.options.meta;
|
|
91
|
-
const meta = typeof metaOption === 'function' ? metaOption() : (metaOption ?? '');
|
|
92
|
-
|
|
93
|
-
const lines: string[] = [spreadLine(title, meta, width), ''];
|
|
94
|
-
const start = this.scroller.offset;
|
|
95
|
-
for (let index = start; index < start + viewport.visibleCount; index++) {
|
|
96
|
-
lines.push(body[index] ?? '');
|
|
97
|
-
}
|
|
98
|
-
if (viewport.showScroll) {
|
|
99
|
-
lines.push(fitLine(this.theme.fg('dim', `${BODY_INDENT}(${this.scroller.visibleEnd}/${body.length})`), width));
|
|
100
|
-
}
|
|
101
|
-
if (description.length > 0) lines.push('', ...description);
|
|
102
|
-
return lines;
|
|
103
|
-
}
|
|
104
|
-
}
|
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Mouse-wheel input shared by the Usage and Injections views.
|
|
3
|
-
*
|
|
4
|
-
* Pi enables mouse reporting only in fullscreen (alt-screen) mode, where its
|
|
5
|
-
* viewport forwards wheel reports to the focused overlay instead of consuming
|
|
6
|
-
* them. In regular mode the terminal keeps the wheel for its own scrollback and
|
|
7
|
-
* no report ever reaches a view, so the parser simply never matches there.
|
|
8
|
-
*/
|
|
9
|
-
import type { TUI } from '@earendil-works/pi-tui';
|
|
10
|
-
|
|
11
|
-
/** Lines one notch scrolls when the TUI exposes no step of its own. */
|
|
12
|
-
export const DEFAULT_WHEEL_SCROLL_LINES = 3;
|
|
13
|
-
|
|
14
|
-
/** SGR wheel report: `ESC [ < button ; column ; row` closed by `M` or `m`. */
|
|
15
|
-
// biome-ignore lint/suspicious/noControlCharactersInRegex: wheel reports begin with the escape byte.
|
|
16
|
-
const SGR_WHEEL_PATTERN = /^\x1b\[<(\d+);\d+;\d+[Mm]$/;
|
|
17
|
-
|
|
18
|
-
/** Legacy X10 wheel report: `ESC [ M` plus offset-encoded button, column, and row bytes. */
|
|
19
|
-
const X10_PREFIX = '\x1b[M';
|
|
20
|
-
const X10_LENGTH = 6;
|
|
21
|
-
const X10_BUTTON_INDEX = 3;
|
|
22
|
-
const X10_BYTE_OFFSET = 32;
|
|
23
|
-
|
|
24
|
-
/** Wheel reports set this button bit; the low two bits then carry axis and direction. */
|
|
25
|
-
const WHEEL_BUTTON_BIT = 64;
|
|
26
|
-
const DIRECTION_MASK = 3;
|
|
27
|
-
|
|
28
|
-
/** One notch backwards (up) or forwards (down). */
|
|
29
|
-
export type WheelDirection = -1 | 1;
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Vertical wheel direction encoded in one input chunk, or undefined for every
|
|
33
|
-
* other input, including horizontal notches. Modifier bits are ignored, so a
|
|
34
|
-
* modified notch scrolls like a plain one, as it does in pi's own viewport.
|
|
35
|
-
*/
|
|
36
|
-
export function parseWheelDirection(data: string): WheelDirection | undefined {
|
|
37
|
-
const sgrButton = SGR_WHEEL_PATTERN.exec(data)?.[1];
|
|
38
|
-
if (sgrButton !== undefined) return decodeWheelButton(Number.parseInt(sgrButton, 10));
|
|
39
|
-
if (data.length === X10_LENGTH && data.startsWith(X10_PREFIX)) {
|
|
40
|
-
return decodeWheelButton(data.charCodeAt(X10_BUTTON_INDEX) - X10_BYTE_OFFSET);
|
|
41
|
-
}
|
|
42
|
-
return undefined;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* Lines one notch scrolls in the surrounding TUI.
|
|
47
|
-
*
|
|
48
|
-
* `TuiAltScreen` keeps its `wheelScrollLines` option private and pi never
|
|
49
|
-
* surfaces it, so read it defensively: honoring the real step keeps previews
|
|
50
|
-
* consistent with the transcript viewport, while any pi that hides, renames, or
|
|
51
|
-
* never had the field falls back to the default instead of a contradicting step.
|
|
52
|
-
*/
|
|
53
|
-
export function readWheelScrollLines(tui: TUI): number {
|
|
54
|
-
const lines = (tui as { readonly wheelScrollLines?: unknown }).wheelScrollLines;
|
|
55
|
-
if (typeof lines !== 'number' || !Number.isFinite(lines)) return DEFAULT_WHEEL_SCROLL_LINES;
|
|
56
|
-
return Math.max(1, Math.floor(lines));
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/** Decode one button code, rejecting non-wheel buttons and the horizontal axis. */
|
|
60
|
-
function decodeWheelButton(button: number): WheelDirection | undefined {
|
|
61
|
-
if ((button & WHEEL_BUTTON_BIT) === 0) return undefined;
|
|
62
|
-
const direction = button & DIRECTION_MASK;
|
|
63
|
-
if (direction === 0) return -1;
|
|
64
|
-
if (direction === 1) return 1;
|
|
65
|
-
return undefined;
|
|
66
|
-
}
|