@0xkahi/pi-qol 0.1.1 → 1.0.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.
@@ -0,0 +1,81 @@
1
+ import type { KeybindingsManager, Theme } from '@earendil-works/pi-coding-agent';
2
+ import { type Component, type Focusable, Key, matchesKey, type TUI, truncateToWidth } from '@earendil-works/pi-tui';
3
+ import type { ContextUsageSnapshot, InitialSnapshot } from '../model';
4
+ import { InjectionsView } from './injections-view';
5
+ import { VimNavigation } from './navigation';
6
+ import { UsageView } from './usage-view';
7
+
8
+ export type ContextViewTab = 'usage' | 'injections';
9
+
10
+ /** One half-height Context View shell that retains both child-tab states. */
11
+ export class ContextViewDialog implements Component, Focusable {
12
+ private readonly usage: UsageView;
13
+ private readonly injections: InjectionsView;
14
+ private readonly navigation = new VimNavigation();
15
+ private active: ContextViewTab = 'usage';
16
+ private _focused = false;
17
+
18
+ constructor(
19
+ private readonly tui: TUI,
20
+ private readonly theme: Theme,
21
+ _keybindings: KeybindingsManager,
22
+ input: { usage: ContextUsageSnapshot; initial: InitialSnapshot; degradedReason?: string },
23
+ done: (result: undefined) => void,
24
+ ) {
25
+ const getRows = () => Math.max(1, Math.floor(tui.terminal.rows / 2) - 1);
26
+ this.usage = new UsageView(this.theme, { usage: input.usage, degradedReason: input.degradedReason }, done, getRows);
27
+ this.injections = new InjectionsView(this.theme, { snapshot: input.initial, degradedReason: input.degradedReason }, done, getRows);
28
+ }
29
+
30
+ get focused(): boolean {
31
+ return this._focused;
32
+ }
33
+
34
+ get activeTab(): ContextViewTab {
35
+ return this.active;
36
+ }
37
+
38
+ set focused(value: boolean) {
39
+ this._focused = value;
40
+ }
41
+
42
+ invalidate(): void {
43
+ this.usage.invalidate();
44
+ this.injections.invalidate();
45
+ }
46
+
47
+ handleInput(data: string): void {
48
+ if (matchesKey(data, Key.tab)) {
49
+ this.switchTab(1);
50
+ } else if (matchesKey(data, Key.shift('tab'))) {
51
+ this.switchTab(-1);
52
+ } else {
53
+ const navigation = this.navigation.consume(data);
54
+ if (navigation.action) this.child().handleNavigation(navigation.action);
55
+ else if (!navigation.handled) this.child().handleInput(data);
56
+ }
57
+ this.tui.requestRender();
58
+ }
59
+
60
+ render(width: number): string[] {
61
+ const lines = this.child().render(width);
62
+ const tabLine = this.renderTabs(width);
63
+ return lines.length === 0 ? [tabLine] : [lines[0] ?? '', tabLine, ...lines.slice(1)];
64
+ }
65
+
66
+ private switchTab(_direction: -1 | 1): void {
67
+ this.active = this.active === 'usage' ? 'injections' : 'usage';
68
+ this.navigation.reset();
69
+ }
70
+
71
+ private renderTabs(width: number): string {
72
+ const usage = this.active === 'usage' ? this.theme.fg('accent', this.theme.bold('[Usage]')) : this.theme.fg('muted', '[Usage]');
73
+ const injections =
74
+ this.active === 'injections' ? this.theme.fg('accent', this.theme.bold('[Injections]')) : this.theme.fg('muted', '[Injections]');
75
+ return truncateToWidth(` ${usage} ${injections}`, Math.max(1, width), '');
76
+ }
77
+
78
+ private child(): UsageView | InjectionsView {
79
+ return this.active === 'usage' ? this.usage : this.injections;
80
+ }
81
+ }
@@ -0,0 +1,257 @@
1
+ /** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
2
+ /**
3
+ * Pure presentation model for the Injections view: flattened rows and
4
+ * list navigation/scrolling state. No pi or TUI access — unit-testable.
5
+ */
6
+ import type { InitialSnapshot, InjectionItem } from '../model';
7
+
8
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: terminal sanitizer intentionally matches control bytes.
9
+ const TERMINAL_STRING_SEQUENCE = /(?:\u001B[\]PX^_]|[\u0090\u0098\u009D\u009E\u009F])[\s\S]*?(?:\u0007|\u001B\\|\u009C)/g;
10
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: terminal sanitizer intentionally matches control bytes.
11
+ const TERMINAL_CSI_SEQUENCE = /(?:\u001B\[|\u009B)[\u0030-\u003F]*[\u0020-\u002F]*[\u0040-\u007E]/g;
12
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: terminal sanitizer intentionally matches control bytes.
13
+ const TERMINAL_ESCAPE_SEQUENCE = /\u001B[\u0020-\u002F]*[\u0030-\u007E]/g;
14
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: terminal sanitizer intentionally matches control bytes.
15
+ const TERMINAL_CONTROL_CHARACTER = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/g;
16
+
17
+ /** One flattened list row derived from the snapshot hierarchy. */
18
+ export type InjectionRow =
19
+ | {
20
+ readonly kind: 'group';
21
+ readonly label: string;
22
+ readonly tokens: number;
23
+ readonly depth: 0;
24
+ }
25
+ | {
26
+ readonly kind: 'item';
27
+ readonly label: string;
28
+ readonly tokens: number;
29
+ /** One for items and two for constituent sub-items. */
30
+ readonly depth: 1 | 2;
31
+ /** Whether this row is the final sibling at its depth. */
32
+ readonly isLast: boolean;
33
+ /** Whether a depth-two row's parent has a following sibling. */
34
+ readonly parentContinues?: boolean;
35
+ /** Stable preview target id from the snapshot. */
36
+ readonly itemId: string;
37
+ }
38
+ | {
39
+ readonly kind: 'separator';
40
+ readonly label: '';
41
+ readonly tokens: 0;
42
+ readonly depth: 0;
43
+ }
44
+ | {
45
+ readonly kind: 'total';
46
+ readonly label: 'TOTAL';
47
+ readonly tokens: number;
48
+ readonly depth: 0;
49
+ };
50
+
51
+ /** Index snapshot items (including sub-items) by id for preview lookup. */
52
+ export function collectItemsById(snapshot: InitialSnapshot): Map<string, InjectionItem> {
53
+ const items = new Map<string, InjectionItem>();
54
+ for (const group of snapshot.groups) {
55
+ for (const item of group.items) {
56
+ items.set(item.id, item);
57
+ for (const child of item.children ?? []) items.set(child.id, child);
58
+ }
59
+ }
60
+ return items;
61
+ }
62
+
63
+ /** Normalize whitespace and remove terminal control sequences from raw preview text. */
64
+ export function normalizePreviewText(text: string): string {
65
+ return text
66
+ .replaceAll('\r\n', '\n')
67
+ .replaceAll('\r', '\n')
68
+ .replaceAll('\t', ' ')
69
+ .replace(TERMINAL_STRING_SEQUENCE, '')
70
+ .replace(TERMINAL_CSI_SEQUENCE, '')
71
+ .replace(TERMINAL_ESCAPE_SEQUENCE, '')
72
+ .replace(TERMINAL_CONTROL_CHARACTER, '');
73
+ }
74
+
75
+ /** Sanitize dynamic text for one terminal line and collapse embedded whitespace. */
76
+ export function normalizeInlineText(text: string): string {
77
+ return normalizePreviewText(text).replace(/\s+/g, ' ').trim();
78
+ }
79
+
80
+ /** Flatten snapshot groups into rows separated from the non-selectable Initial total. */
81
+ export function buildInjectionRows(snapshot: InitialSnapshot): InjectionRow[] {
82
+ const rows: InjectionRow[] = [];
83
+ for (const group of snapshot.groups) {
84
+ rows.push({
85
+ kind: 'group',
86
+ label: group.source.label,
87
+ tokens: group.totalTokens,
88
+ depth: 0,
89
+ });
90
+ group.items.forEach((item, itemIndex) => {
91
+ const isLastItem = itemIndex === group.items.length - 1;
92
+ rows.push({
93
+ kind: 'item',
94
+ label: item.label,
95
+ tokens: item.tokens,
96
+ depth: 1,
97
+ isLast: isLastItem,
98
+ itemId: item.id,
99
+ });
100
+ const children = item.children ?? [];
101
+ children.forEach((child, childIndex) => {
102
+ rows.push({
103
+ kind: 'item',
104
+ label: child.label,
105
+ tokens: child.tokens,
106
+ depth: 2,
107
+ isLast: childIndex === children.length - 1,
108
+ parentContinues: !isLastItem,
109
+ itemId: child.id,
110
+ });
111
+ });
112
+ });
113
+ }
114
+ rows.push({ kind: 'separator', label: '', tokens: 0, depth: 0 });
115
+ rows.push({ kind: 'total', label: 'TOTAL', tokens: snapshot.totalTokens, depth: 0 });
116
+ return rows;
117
+ }
118
+
119
+ /**
120
+ * Selection and scroll-window state over fixed rows. A trailing summary can
121
+ * participate in scrolling without being included in selection navigation.
122
+ */
123
+ export class ListNavigator {
124
+ private readonly rowCount: number;
125
+ private readonly selectableRowCount: number;
126
+ private visibleCount: number;
127
+ private selectedIndex = 0;
128
+ private scrollOffset = 0;
129
+
130
+ public constructor(rowCount: number, visibleCount: number, selectableRowCount = rowCount) {
131
+ this.rowCount = Math.max(0, rowCount);
132
+ this.selectableRowCount = Math.min(this.rowCount, Math.max(0, selectableRowCount));
133
+ this.visibleCount = Math.max(1, visibleCount);
134
+ }
135
+
136
+ public get selected(): number {
137
+ return this.selectedIndex;
138
+ }
139
+
140
+ public get selectedOrdinal(): number {
141
+ return this.selectedIndex;
142
+ }
143
+
144
+ public get selectableCount(): number {
145
+ return this.selectableRowCount;
146
+ }
147
+
148
+ public get offset(): number {
149
+ return this.scrollOffset;
150
+ }
151
+
152
+ public get windowSize(): number {
153
+ return Math.min(this.visibleCount, this.rowCount);
154
+ }
155
+
156
+ /** One-based final row currently visible, suitable for a scroll counter. */
157
+ public get visibleEnd(): number {
158
+ return Math.min(this.rowCount, this.scrollOffset + this.windowSize);
159
+ }
160
+
161
+ public get hasOverflow(): boolean {
162
+ return this.rowCount > this.visibleCount;
163
+ }
164
+
165
+ public setVisibleCount(count: number): void {
166
+ this.visibleCount = Math.max(1, count);
167
+ this.ensureVisible();
168
+ }
169
+
170
+ public moveBy(delta: number): boolean {
171
+ return this.moveTo(this.selectedIndex + delta);
172
+ }
173
+
174
+ public moveTo(index: number): boolean {
175
+ if (this.selectableRowCount === 0) return false;
176
+ const next = Math.min(this.selectableRowCount - 1, Math.max(0, index));
177
+ if (next === this.selectedIndex) return false;
178
+ this.selectedIndex = next;
179
+ this.ensureVisible();
180
+ return true;
181
+ }
182
+
183
+ public page(direction: -1 | 1): boolean {
184
+ return this.moveBy(direction * Math.max(1, this.visibleCount - 1));
185
+ }
186
+
187
+ private ensureVisible(): void {
188
+ const maxOffset = Math.max(0, this.rowCount - this.visibleCount);
189
+ if (this.selectedIndex < this.scrollOffset) {
190
+ this.scrollOffset = this.selectedIndex;
191
+ } else if (this.selectedIndex >= this.scrollOffset + this.visibleCount) {
192
+ this.scrollOffset = this.selectedIndex - this.visibleCount + 1;
193
+ }
194
+
195
+ const trailingRows = this.rowCount - this.selectedIndex - 1;
196
+ if (this.selectedIndex === this.selectableRowCount - 1 && trailingRows < this.visibleCount) {
197
+ this.scrollOffset = maxOffset;
198
+ }
199
+ this.scrollOffset = Math.min(maxOffset, Math.max(0, this.scrollOffset));
200
+ }
201
+ }
202
+
203
+ /**
204
+ * Scroll-only window over wrapped preview lines. Extent is re-declared each
205
+ * render (wrapping depends on width); the offset is clamped to stay valid.
206
+ */
207
+ export class PreviewScroller {
208
+ private lineCount = 0;
209
+ private visibleCount = 1;
210
+ private offsetValue = 0;
211
+
212
+ public get offset(): number {
213
+ return this.offsetValue;
214
+ }
215
+
216
+ public get windowSize(): number {
217
+ return Math.min(this.visibleCount, this.lineCount);
218
+ }
219
+
220
+ /** One-based final line currently visible, suitable for a progress counter. */
221
+ public get visibleEnd(): number {
222
+ return Math.min(this.lineCount, this.offsetValue + this.windowSize);
223
+ }
224
+
225
+ public get hasOverflow(): boolean {
226
+ return this.lineCount > this.visibleCount;
227
+ }
228
+
229
+ public get maxOffset(): number {
230
+ return Math.max(0, this.lineCount - this.visibleCount);
231
+ }
232
+
233
+ public setExtent(lineCount: number, visibleCount: number): void {
234
+ this.lineCount = Math.max(0, lineCount);
235
+ this.visibleCount = Math.max(1, visibleCount);
236
+ this.offsetValue = Math.min(this.maxOffset, this.offsetValue);
237
+ }
238
+
239
+ public scrollBy(delta: number): boolean {
240
+ return this.scrollTo(this.offsetValue + delta);
241
+ }
242
+
243
+ public scrollTo(offset: number): boolean {
244
+ const next = Math.min(this.maxOffset, Math.max(0, offset));
245
+ if (next === this.offsetValue) return false;
246
+ this.offsetValue = next;
247
+ return true;
248
+ }
249
+
250
+ public page(direction: -1 | 1): boolean {
251
+ return this.scrollBy(direction * Math.max(1, this.visibleCount - 1));
252
+ }
253
+
254
+ public reset(): void {
255
+ this.offsetValue = 0;
256
+ }
257
+ }