@mrclrchtr/supi-ask-user 4.10.0 → 5.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.
package/README.md CHANGED
@@ -98,7 +98,9 @@ The form shows context-specific key hints at the bottom.
98
98
 
99
99
  | Key | Action |
100
100
  |---|---|
101
- | `↑` `↓` | Move through choices or review rows |
101
+ | `↑` `↓` | Move through choices or review rows; at the first or last row, scroll surrounding content |
102
+ | `Page Up` / `Page Down` | Scroll an overflowing choice or review form by one page |
103
+ | `Alt+Page Up` / `Alt+Page Down` | Scroll the outer form while editing text or comments |
102
104
  | `Space` | Select a single choice or toggle a multi-select option |
103
105
  | `Enter` | Accept an answer, save text or comments, edit a review row, or submit the form |
104
106
  | `←` `→` | Move between choice questions; `←` returns from review |
@@ -108,7 +110,7 @@ The form shows context-specific key hints at the bottom.
108
110
  | `u` / `Alt+U` | Mark the question unanswered (`Alt+U` for text questions) |
109
111
  | `Esc` | Cancel the form; in a comment editor, discard unsaved comment text |
110
112
 
111
- On wide terminals, option details appear beside the choices. On narrow terminals, they appear below the choices.
113
+ On wide terminals, option details appear beside the choices. On narrow terminals, they appear below the choices. If a form is taller than its inline height limit, Ask User keeps the focused row visible and shows a scroll position indicator.
112
114
 
113
115
  ## Requirements, defaults, and limits
114
116
 
@@ -28,6 +28,7 @@ pnpm add @mrclrchtr/supi-core
28
28
  - `loadSupiConfig()` — merged config with resolution order `defaults <- global <- project`
29
29
  - `loadSupiConfigForScope()` — load one scope at a time for settings UIs
30
30
  - `writeSupiConfig()` — persist values
31
+ - `replaceSupiConfigSection()` — replace one nested section while preserving other sections
31
32
  - `removeSupiConfigKey()` — remove a key or override
32
33
 
33
34
  Config file locations:
@@ -49,6 +50,7 @@ Config file locations:
49
50
 
50
51
  - context-provider registry for `/supi-context`
51
52
  - debug-event registry and monotonic phase timers for producers that want shared debug capture
53
+ - optional Debug Operation IDs for exact, directly owned public Tool-call correlation; ambient events stay uncorrelated
52
54
  - settings registry used by `/supi-settings`
53
55
 
54
56
  ### Project and session helpers
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrclrchtr/supi-core",
3
- "version": "4.10.0",
3
+ "version": "5.0.0",
4
4
  "description": "Shared settings, configuration, reporting, and session infrastructure",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -148,6 +148,37 @@ export function writeSupiConfig(
148
148
  fs.writeFileSync(configPath, `${JSON.stringify(existing, null, 2)}\n`, "utf-8");
149
149
  }
150
150
 
151
+ /**
152
+ * Replace one complete config section while preserving other sections.
153
+ *
154
+ * This is useful for nested settings that must remove stale keys as part of
155
+ * one update. An empty section is removed from the config file.
156
+ */
157
+ export function replaceSupiConfigSection(
158
+ loc: SupiConfigLocation,
159
+ value: Record<string, unknown>,
160
+ options?: SupiConfigOptions,
161
+ ): void {
162
+ const configPath = getSupiConfigPath(loc.scope, loc.cwd, options);
163
+ const existing = readJsonFile(configPath) ?? {};
164
+
165
+ if (Object.keys(value).length > 0) existing[loc.section] = value;
166
+ else delete existing[loc.section];
167
+
168
+ const content = Object.keys(existing).length > 0 ? `${JSON.stringify(existing, null, 2)}\n` : "";
169
+ if (content) {
170
+ fs.mkdirSync(path.dirname(configPath), { recursive: true });
171
+ fs.writeFileSync(configPath, content, "utf-8");
172
+ return;
173
+ }
174
+
175
+ try {
176
+ fs.unlinkSync(configPath);
177
+ } catch {
178
+ // File may not exist.
179
+ }
180
+ }
181
+
151
182
  /**
152
183
  * Remove a key from a config section.
153
184
  * Used by `interval default` to remove the project override.
@@ -1,10 +1,12 @@
1
1
  // supi-core config domain — config loading.
2
2
  export type { SupiConfigLocation, SupiConfigOptions } from "./config/config.ts";
3
3
  export {
4
+ getSupiConfigPath,
4
5
  loadSupiConfig,
5
6
  loadSupiConfigForScope,
6
7
  loadSupiConfigSectionForScope,
7
8
  readJsonFile,
8
9
  removeSupiConfigKey,
10
+ replaceSupiConfigSection,
9
11
  writeSupiConfig,
10
12
  } from "./config/config.ts";
@@ -25,6 +25,8 @@ export const DEBUG_REGISTRY_DEFAULTS: DebugRegistryConfig = {
25
25
  };
26
26
 
27
27
  export interface DebugEventInput {
28
+ /** Opaque identity for events directly owned by one public Tool call. */
29
+ operationId?: string;
28
30
  source: string;
29
31
  level: DebugLevel;
30
32
  category: string;
@@ -42,6 +44,8 @@ export interface DebugEvent extends DebugEventInput {
42
44
  }
43
45
 
44
46
  export interface DebugEventQuery {
47
+ /** Match one exact Debug Operation ID. */
48
+ operationId?: string;
45
49
  source?: string;
46
50
  level?: DebugLevel;
47
51
  category?: string;
@@ -53,6 +57,7 @@ export interface DebugEventQuery {
53
57
  export interface DebugEventView {
54
58
  id: number;
55
59
  timestamp: number;
60
+ operationId?: string;
56
61
  source: string;
57
62
  level: DebugLevel;
58
63
  category: string;
@@ -84,6 +89,7 @@ interface DebugRegistryState {
84
89
  }
85
90
 
86
91
  const REGISTRY_KEY = Symbol.for("@mrclrchtr/supi-core/debug-registry");
92
+ const DEBUG_OPERATION_ID_RE = /^op-[A-Za-z0-9_-]{21}[AQgw]$/;
87
93
  const SECRET_KEY_RE = /(?:token|password|passwd|secret|api[_-]?key|authorization|credential)/i;
88
94
  const ENV_SECRET_RE =
89
95
  /\b([A-Za-z0-9_]*(?:token|password|passwd|secret|api[_-]?key|authorization|credential)[A-Za-z0-9_]*)=(?:'[^']*'|"[^"]*"|\S+)/gi;
@@ -135,11 +141,17 @@ export function isDebugLevel(value: unknown): value is DebugLevel {
135
141
  return value === "debug" || value === "info" || value === "warning" || value === "error";
136
142
  }
137
143
 
138
- /** Match a debug event against the supported source, level, and category filters. */
144
+ /** Return whether a value has the exact 16-byte base64url Debug Operation ID form. */
145
+ export function isDebugOperationId(value: unknown): value is string {
146
+ return typeof value === "string" && DEBUG_OPERATION_ID_RE.test(value);
147
+ }
148
+
149
+ /** Match a debug event against the supported exact filters. */
139
150
  export function matchesDebugEventQuery(
140
- event: Pick<DebugEventView, "source" | "level" | "category">,
141
- query: Pick<DebugEventQuery, "source" | "level" | "category">,
151
+ event: Pick<DebugEventView, "operationId" | "source" | "level" | "category">,
152
+ query: Pick<DebugEventQuery, "operationId" | "source" | "level" | "category">,
142
153
  ): boolean {
154
+ if (query.operationId && event.operationId !== query.operationId) return false;
143
155
  if (query.source && event.source !== query.source) return false;
144
156
  if (query.level && event.level !== query.level) return false;
145
157
  if (query.category && event.category !== query.category) return false;
@@ -197,6 +209,7 @@ function toSanitizedView(event: DebugEvent): DebugEventView {
197
209
  return {
198
210
  id: event.id,
199
211
  timestamp: event.timestamp,
212
+ operationId: event.operationId,
200
213
  source: event.source,
201
214
  level: event.level,
202
215
  category: event.category,
@@ -216,6 +229,9 @@ export function subscribeDebugEvents(listener: DebugEventListener): () => void {
216
229
  /** Record a session-local debug event if debugging is enabled. */
217
230
  export function recordDebugEvent(input: DebugEventInput): DebugEvent | null {
218
231
  const state = getState();
232
+ if (input.operationId !== undefined && !isDebugOperationId(input.operationId)) {
233
+ return null;
234
+ }
219
235
  if (!state.config.enabled) {
220
236
  return null;
221
237
  }
@@ -41,7 +41,10 @@ export interface SettingsApplyResult {
41
41
  */
42
42
  export interface SettingsModule {
43
43
  id: string;
44
+ /** Human-readable section label shown in the UI. */
44
45
  label: string;
46
+ /** Optional label that groups this module within its section. */
47
+ subsection?: string;
45
48
  read(context: SettingsContext): Promise<SettingsSnapshot>;
46
49
  apply(request: SettingsActionRequest): Promise<SettingsApplyResult>;
47
50
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrclrchtr/supi-ask-user",
3
- "version": "4.10.0",
3
+ "version": "5.0.0",
4
4
  "description": "Structured choice and text forms for agent-user decisions",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -32,7 +32,7 @@
32
32
  "!__tests__"
33
33
  ],
34
34
  "dependencies": {
35
- "@mrclrchtr/supi-core": "4.10.0"
35
+ "@mrclrchtr/supi-core": "5.0.0"
36
36
  },
37
37
  "bundledDependencies": [
38
38
  "@mrclrchtr/supi-core"
@@ -12,6 +12,7 @@ import {
12
12
  import type { NormalizedChoiceQuestion } from "../types.ts";
13
13
  import { renderFormFrame } from "./form-render.ts";
14
14
  import { defaultChoiceRowIndex, type FormMode, focusForMode } from "./form-view.ts";
15
+ import { calculateFormHeightLimit } from "./form-viewport.ts";
15
16
  import type { FormArgs } from "./types.ts";
16
17
 
17
18
  type QuestionnaireMode = "choice" | "text" | "review";
@@ -44,8 +45,14 @@ export class AskUserForm implements Component, Focusable {
44
45
  private reviewFocusIndex = 0;
45
46
  private closed: boolean = false;
46
47
  private cachedWidth: number | undefined;
48
+ private cachedTerminalRows: number | undefined;
47
49
  private cachedEditorFocused: boolean | undefined;
48
50
  private cachedLines: string[] | undefined;
51
+ private scrollOffset = 0;
52
+ private viewportPageSize = 1;
53
+ private viewportMaxScrollOffset = 0;
54
+ private viewportOverflow = false;
55
+ private revealFocusedContent = true;
49
56
  private commentEdit: CommentEdit | undefined;
50
57
  private returnToReviewAfterEdit: boolean = false;
51
58
  private pendingEsc: boolean = false;
@@ -75,10 +82,15 @@ export class AskUserForm implements Component, Focusable {
75
82
  const mode = this.currentMode();
76
83
  const focus = focusForMode(mode);
77
84
  const editorFocused = this.focused && focus === "editor";
85
+ const terminalRows = this.args.tui.terminal.rows;
86
+ const dimensionsChanged =
87
+ this.cachedWidth !== undefined &&
88
+ (this.cachedWidth !== width || this.cachedTerminalRows !== terminalRows);
78
89
  if (isFocusable(this.editor)) this.editor.focused = editorFocused;
79
90
 
80
91
  if (
81
92
  this.cachedWidth === width &&
93
+ this.cachedTerminalRows === terminalRows &&
82
94
  this.cachedEditorFocused === editorFocused &&
83
95
  this.cachedLines
84
96
  ) {
@@ -86,9 +98,13 @@ export class AskUserForm implements Component, Focusable {
86
98
  }
87
99
 
88
100
  this.cachedWidth = width;
101
+ this.cachedTerminalRows = terminalRows;
89
102
  this.cachedEditorFocused = editorFocused;
90
- this.cachedLines = renderFormFrame({
103
+ const frame = renderFormFrame({
91
104
  width,
105
+ maxHeight: calculateFormHeightLimit(terminalRows),
106
+ scrollOffset: this.scrollOffset,
107
+ revealFocus: this.revealFocusedContent || dimensionsChanged,
92
108
  theme: this.args.theme,
93
109
  controller: this.args.controller,
94
110
  mode,
@@ -100,6 +116,12 @@ export class AskUserForm implements Component, Focusable {
100
116
  editorLabel: this.currentEditorLabel(),
101
117
  editorContext: this.commentEdit?.context,
102
118
  });
119
+ this.scrollOffset = frame.viewport.scrollOffset;
120
+ this.viewportPageSize = frame.viewport.pageSize;
121
+ this.viewportMaxScrollOffset = frame.viewport.maxScrollOffset;
122
+ this.viewportOverflow = frame.viewport.overflow;
123
+ this.revealFocusedContent = false;
124
+ this.cachedLines = frame.lines;
103
125
  return this.cachedLines;
104
126
  }
105
127
 
@@ -112,6 +134,7 @@ export class AskUserForm implements Component, Focusable {
112
134
  }
113
135
 
114
136
  if (this.handleEscapeKey(data)) return;
137
+ if (this.handleViewportKey(data)) return;
115
138
  if (this.handleNavigationKey(data)) return;
116
139
 
117
140
  if (this.isCommentEditorMode()) {
@@ -138,7 +161,7 @@ export class AskUserForm implements Component, Focusable {
138
161
 
139
162
  if (this.editorHandlesEscape && (this.baseMode === "text" || this.isCommentEditorMode())) {
140
163
  this.editor.handleInput(data);
141
- if (!this.closed) this.refresh();
164
+ if (!this.closed) this.refreshWithFocusReveal();
142
165
  return true;
143
166
  }
144
167
 
@@ -177,6 +200,19 @@ export class AskUserForm implements Component, Focusable {
177
200
  }
178
201
  }
179
202
 
203
+ private handleViewportKey(data: string): boolean {
204
+ if (!this.viewportOverflow) return false;
205
+ const editorFocused = focusForMode(this.currentMode()) === "editor";
206
+ const pageUp = editorFocused ? Key.alt("pageUp") : Key.pageUp;
207
+ const pageDown = editorFocused ? Key.alt("pageDown") : Key.pageDown;
208
+ const direction = matchesKey(data, pageUp) ? -1 : matchesKey(data, pageDown) ? 1 : 0;
209
+ if (direction === 0) return false;
210
+
211
+ const pageDelta = Math.max(1, this.viewportPageSize - 1);
212
+ this.scrollViewportByLines(direction * pageDelta);
213
+ return true;
214
+ }
215
+
180
216
  private handleNavigationKey(data: string): boolean {
181
217
  if (this.isCommentEditorMode()) return false;
182
218
 
@@ -251,14 +287,22 @@ export class AskUserForm implements Component, Focusable {
251
287
  }
252
288
 
253
289
  if (matchesKey(data, Key.up)) {
254
- this.reviewFocusIndex = Math.max(0, this.reviewFocusIndex - 1);
255
- this.refresh();
290
+ if (this.reviewFocusIndex === 0) {
291
+ this.scrollViewportByLines(-1);
292
+ return;
293
+ }
294
+ this.reviewFocusIndex -= 1;
295
+ this.refreshWithFocusReveal();
256
296
  return;
257
297
  }
258
298
 
259
299
  if (matchesKey(data, Key.down)) {
260
- this.reviewFocusIndex = Math.min(submitIndex, this.reviewFocusIndex + 1);
261
- this.refresh();
300
+ if (this.reviewFocusIndex === submitIndex) {
301
+ this.scrollViewportByLines(1);
302
+ return;
303
+ }
304
+ this.reviewFocusIndex += 1;
305
+ this.refreshWithFocusReveal();
262
306
  return;
263
307
  }
264
308
 
@@ -272,18 +316,7 @@ export class AskUserForm implements Component, Focusable {
272
316
  private handleChoiceKey(data: string): void {
273
317
  const question = this.args.controller.currentQuestion;
274
318
  if (question.type !== "choice") return;
275
-
276
- if (matchesKey(data, Key.up)) {
277
- this.choiceFocusIndex = Math.max(0, this.choiceFocusIndex - 1);
278
- this.refresh();
279
- return;
280
- }
281
-
282
- if (matchesKey(data, Key.down)) {
283
- this.choiceFocusIndex = Math.min(question.options.length - 1, this.choiceFocusIndex + 1);
284
- this.refresh();
285
- return;
286
- }
319
+ if (this.handleChoiceNavigation(data, question.options.length)) return;
287
320
 
288
321
  if (matchesKey(data, Key.space)) {
289
322
  if (question.multi) {
@@ -291,7 +324,7 @@ export class AskUserForm implements Component, Focusable {
291
324
  } else {
292
325
  this.args.controller.selectChoiceOption(question, this.choiceFocusIndex);
293
326
  }
294
- this.refresh();
327
+ this.refreshWithFocusReveal();
295
328
  return;
296
329
  }
297
330
 
@@ -305,7 +338,7 @@ export class AskUserForm implements Component, Focusable {
305
338
 
306
339
  if (data === "u") {
307
340
  this.args.controller.markCurrentQuestionUnanswered();
308
- this.refresh();
341
+ this.refreshWithFocusReveal();
309
342
  return;
310
343
  }
311
344
 
@@ -319,6 +352,28 @@ export class AskUserForm implements Component, Focusable {
319
352
  }
320
353
  }
321
354
 
355
+ private handleChoiceNavigation(data: string, optionCount: number): boolean {
356
+ if (matchesKey(data, Key.up)) {
357
+ if (this.choiceFocusIndex === 0) this.scrollViewportByLines(-1);
358
+ else {
359
+ this.choiceFocusIndex -= 1;
360
+ this.refreshWithFocusReveal();
361
+ }
362
+ return true;
363
+ }
364
+
365
+ if (matchesKey(data, Key.down)) {
366
+ if (this.choiceFocusIndex === optionCount - 1) this.scrollViewportByLines(1);
367
+ else {
368
+ this.choiceFocusIndex += 1;
369
+ this.refreshWithFocusReveal();
370
+ }
371
+ return true;
372
+ }
373
+
374
+ return false;
375
+ }
376
+
322
377
  // ── Text screen ─────────────────────────────────────────────────
323
378
 
324
379
  private handleTextKey(data: string): void {
@@ -327,7 +382,7 @@ export class AskUserForm implements Component, Focusable {
327
382
  if (data === "u") {
328
383
  this.args.controller.markCurrentQuestionUnanswered();
329
384
  this.setEditorText("");
330
- this.refresh();
385
+ this.refreshWithFocusReveal();
331
386
  return;
332
387
  }
333
388
  if (data === "c") {
@@ -346,10 +401,11 @@ export class AskUserForm implements Component, Focusable {
346
401
  if (matchesKey(data, Key.alt("u"))) {
347
402
  this.args.controller.markCurrentQuestionUnanswered();
348
403
  this.setEditorText("");
349
- this.refresh();
404
+ this.refreshWithFocusReveal();
350
405
  return;
351
406
  }
352
407
 
408
+ if (isFocusable(this.editor)) this.requestFocusReveal();
353
409
  this.editor.handleInput(data);
354
410
  this.refresh();
355
411
  }
@@ -357,6 +413,7 @@ export class AskUserForm implements Component, Focusable {
357
413
  // ── Comment editors ─────────────────────────────────────────────
358
414
 
359
415
  private handleCommentEditorKey(data: string): void {
416
+ if (isFocusable(this.editor)) this.requestFocusReveal();
360
417
  this.editor.handleInput(data);
361
418
  this.refresh();
362
419
  }
@@ -404,6 +461,7 @@ export class AskUserForm implements Component, Focusable {
404
461
  context: this.args.controller.questionnaire.title ?? "Form",
405
462
  };
406
463
  this.setEditorText(this.args.controller.comment ?? "");
464
+ this.resetViewport();
407
465
  this.refresh();
408
466
  }
409
467
 
@@ -415,6 +473,7 @@ export class AskUserForm implements Component, Focusable {
415
473
  returnChoiceFocusIndex: this.choiceFocusIndex,
416
474
  };
417
475
  this.setEditorText(this.args.controller.getQuestionComment(questionId) ?? "");
476
+ this.resetViewport();
418
477
  this.refresh();
419
478
  }
420
479
 
@@ -429,6 +488,7 @@ export class AskUserForm implements Component, Focusable {
429
488
  returnChoiceFocusIndex: optionIndex,
430
489
  };
431
490
  this.setEditorText(this.args.controller.getOptionComment(question.id, option.value) ?? "");
491
+ this.resetViewport();
432
492
  this.refresh();
433
493
  }
434
494
 
@@ -441,6 +501,7 @@ export class AskUserForm implements Component, Focusable {
441
501
  case "form":
442
502
  this.baseMode = "review";
443
503
  this.setEditorText("");
504
+ this.resetViewport();
444
505
  return;
445
506
  case "question":
446
507
  this.syncCurrentQuestion();
@@ -461,6 +522,7 @@ export class AskUserForm implements Component, Focusable {
461
522
  this.baseMode = "review";
462
523
  this.reviewFocusIndex = this.args.controller.questionnaire.questions.length;
463
524
  this.setEditorText("");
525
+ this.resetViewport();
464
526
  this.refresh();
465
527
  return;
466
528
  }
@@ -471,6 +533,7 @@ export class AskUserForm implements Component, Focusable {
471
533
  this.baseMode = "review";
472
534
  // Focus the Submit row by default so Enter submits immediately.
473
535
  this.reviewFocusIndex = this.args.controller.questionnaire.questions.length;
536
+ this.resetViewport();
474
537
  this.refresh();
475
538
  return;
476
539
  }
@@ -499,6 +562,7 @@ export class AskUserForm implements Component, Focusable {
499
562
  if (question.type === "text") {
500
563
  this.baseMode = "text";
501
564
  this.setEditorText(this.args.controller.getTextAnswer(question.id));
565
+ this.resetViewport();
502
566
  return;
503
567
  }
504
568
 
@@ -507,6 +571,7 @@ export class AskUserForm implements Component, Focusable {
507
571
  this.choiceFocusIndex =
508
572
  this.choiceFocusByQuestionId.get(question.id) ??
509
573
  defaultChoiceRowIndex(this.args.controller, question);
574
+ this.resetViewport();
510
575
  }
511
576
 
512
577
  private saveCurrentChoiceFocus(): void {
@@ -552,6 +617,32 @@ export class AskUserForm implements Component, Focusable {
552
617
  }
553
618
  }
554
619
 
620
+ private scrollViewportByLines(lines: number): void {
621
+ if (!this.viewportOverflow) return;
622
+ const nextOffset = Math.max(
623
+ 0,
624
+ Math.min(this.viewportMaxScrollOffset, this.scrollOffset + lines),
625
+ );
626
+ if (nextOffset === this.scrollOffset) return;
627
+ this.scrollOffset = nextOffset;
628
+ this.revealFocusedContent = false;
629
+ this.refresh();
630
+ }
631
+
632
+ private resetViewport(): void {
633
+ this.scrollOffset = 0;
634
+ this.revealFocusedContent = true;
635
+ }
636
+
637
+ private requestFocusReveal(): void {
638
+ this.revealFocusedContent = true;
639
+ }
640
+
641
+ private refreshWithFocusReveal(): void {
642
+ this.requestFocusReveal();
643
+ this.refresh();
644
+ }
645
+
555
646
  private finish(): void {
556
647
  if (this.closed) return;
557
648
  this.closed = true;
@@ -0,0 +1,173 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+ import { CURSOR_MARKER, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
3
+ import type { NormalizedChoiceQuestion } from "../types.ts";
4
+ import type { RenderFormFrameArgs } from "./form-render.ts";
5
+ import {
6
+ padRight,
7
+ pushWrappedWithPrefix,
8
+ renderMiniBox,
9
+ renderPrompt,
10
+ safeWidth,
11
+ } from "./form-render-primitives.ts";
12
+ import {
13
+ type FormLineRange,
14
+ offsetFormLineRange,
15
+ type RenderedFormSection,
16
+ } from "./form-viewport.ts";
17
+
18
+ export function renderChoiceScreen(args: RenderFormFrameArgs): RenderedFormSection {
19
+ const lines: string[] = [];
20
+ const question = args.controller.currentQuestion;
21
+
22
+ if (question.type !== "choice") return { lines };
23
+
24
+ lines.push(...renderPrompt(question.prompt, args.width));
25
+ if (args.controller.isQuestionMarkedUnanswered(question.id)) {
26
+ lines.push("");
27
+ lines.push(args.theme.fg("warning", "Marked unanswered; comments preserved."));
28
+ }
29
+ lines.push("");
30
+
31
+ if (args.detailsText && args.width >= 80) {
32
+ const section = renderChoiceWithDetails(args, question);
33
+ const focusedRange = offsetFormLineRange(section.focusedRange, lines.length);
34
+ lines.push(...section.lines);
35
+ return { lines, focusedRange };
36
+ }
37
+
38
+ let focusedRange: FormLineRange | undefined;
39
+ for (let i = 0; i < question.options.length; i += 1) {
40
+ const start = lines.length;
41
+ lines.push(...renderChoiceOptionLines(args, question, i, args.width));
42
+ if (i === args.choiceFocusIndex) focusedRange = { start, end: lines.length };
43
+ }
44
+
45
+ if (args.detailsText) {
46
+ lines.push("");
47
+ lines.push(...renderDetailsCard(args.theme, args.detailsText, args.width));
48
+ }
49
+
50
+ return { lines, focusedRange };
51
+ }
52
+
53
+ function renderChoiceWithDetails(
54
+ args: RenderFormFrameArgs,
55
+ question: NormalizedChoiceQuestion,
56
+ ): RenderedFormSection {
57
+ const gap = 2;
58
+ const divider = args.theme.fg("borderMuted", "│");
59
+ const dividerWidth = 1;
60
+ const minLeftWidth = 28;
61
+ const preferredDetailsWidth = Math.max(30, Math.floor(args.width * 0.38));
62
+ const rightWidth = Math.max(
63
+ 22,
64
+ Math.min(preferredDetailsWidth, args.width - gap - dividerWidth - gap - minLeftWidth),
65
+ );
66
+ const leftWidth = Math.max(1, args.width - gap - dividerWidth - gap - rightWidth);
67
+
68
+ const optionLines: string[] = [];
69
+ let focusedRange: FormLineRange | undefined;
70
+ for (let i = 0; i < question.options.length; i += 1) {
71
+ const start = optionLines.length;
72
+ optionLines.push(...renderChoiceOptionLines(args, question, i, leftWidth));
73
+ if (i === args.choiceFocusIndex) focusedRange = { start, end: optionLines.length };
74
+ }
75
+
76
+ const detailsLines = renderDetailsCard(args.theme, args.detailsText ?? "", rightWidth);
77
+ const merged: string[] = [];
78
+ const maxRows = Math.max(optionLines.length, detailsLines.length);
79
+ for (let i = 0; i < maxRows; i += 1) {
80
+ const left = optionLines[i] ?? "";
81
+ const right = detailsLines[i] ?? "";
82
+ const mergedLine = `${padRight(left, leftWidth)}${" ".repeat(gap)}${divider}${" ".repeat(gap)}${right}`;
83
+ merged.push(truncateToWidth(mergedLine, args.width));
84
+ }
85
+
86
+ return { lines: merged, focusedRange };
87
+ }
88
+
89
+ function renderChoiceOptionLines(
90
+ args: RenderFormFrameArgs,
91
+ question: NormalizedChoiceQuestion,
92
+ optionIndex: number,
93
+ width: number,
94
+ ): string[] {
95
+ const lines: string[] = [];
96
+ const opt = question.options[optionIndex];
97
+ const focused = optionIndex === args.choiceFocusIndex;
98
+ const selected = args.controller.isOptionSelected(question.id, opt.value);
99
+ const hasComment = !!args.controller.getOptionComment(question.id, opt.value);
100
+
101
+ const marker = choiceMarker(question.multi, selected);
102
+ const isRecommended = question.recommendedIndexes.includes(optionIndex);
103
+ const prefix = focused ? " → " : " ";
104
+ const label = `${marker} ${opt.label}${isRecommended ? " [recommended]" : ""}${hasComment ? " [comment]" : ""}`;
105
+ pushWrappedWithPrefix({
106
+ lines,
107
+ prefix,
108
+ text: focused ? args.theme.fg("accent", label) : label,
109
+ width,
110
+ });
111
+
112
+ if (opt.description) {
113
+ pushWrappedWithPrefix({
114
+ lines,
115
+ prefix: " ",
116
+ text: args.theme.fg("muted", opt.description),
117
+ width,
118
+ });
119
+ }
120
+
121
+ return lines;
122
+ }
123
+
124
+ function choiceMarker(multi: boolean, selected: boolean): string {
125
+ if (multi) return selected ? "[x]" : "[ ]";
126
+ return selected ? "(*)" : "( )";
127
+ }
128
+
129
+ export function renderTextScreen(args: RenderFormFrameArgs): RenderedFormSection {
130
+ const lines: string[] = [];
131
+ const question = args.controller.currentQuestion;
132
+
133
+ if (question.type !== "text") return { lines };
134
+
135
+ lines.push(...renderPrompt(question.prompt, args.width));
136
+ lines.push("");
137
+ lines.push(args.theme.fg("accent", "Your answer"));
138
+ const editorStart = lines.length;
139
+ const editorLines = args.editor.render(safeWidth(args.width));
140
+ lines.push(...editorLines);
141
+ const focusedRange = editorFocusRange(editorLines, editorStart);
142
+
143
+ if (question.placeholder && !args.editor.getText()) {
144
+ lines.push("");
145
+ lines.push(
146
+ ...wrapTextWithAnsi(args.theme.fg("dim", `Placeholder: ${question.placeholder}`), args.width),
147
+ );
148
+ }
149
+
150
+ return { lines, focusedRange };
151
+ }
152
+
153
+ export function renderEditorScreen(args: RenderFormFrameArgs): RenderedFormSection {
154
+ const lines: string[] = [];
155
+ const label = args.editorLabel ?? "Editor";
156
+ const title = args.editorContext ? `${label}: ${args.editorContext}` : label;
157
+ lines.push(args.theme.fg("accent", title));
158
+ const editorStart = lines.length;
159
+ const editorLines = args.editor.render(safeWidth(args.width));
160
+ lines.push(...editorLines);
161
+ return { lines, focusedRange: editorFocusRange(editorLines, editorStart) };
162
+ }
163
+
164
+ function editorFocusRange(editorLines: string[], start: number): FormLineRange {
165
+ const cursorLine = editorLines.findIndex((line) => line.includes(CURSOR_MARKER));
166
+ if (cursorLine >= 0) return { start: start + cursorLine, end: start + cursorLine + 1 };
167
+ return { start, end: start + 1 };
168
+ }
169
+
170
+ function renderDetailsCard(theme: Theme, detailsText: string, width: number): string[] {
171
+ const innerWidth = Math.max(1, safeWidth(width) - 4);
172
+ return renderMiniBox(theme, "Details", renderPrompt(detailsText, innerWidth), width);
173
+ }
@@ -1,20 +1,35 @@
1
1
  import type { Theme } from "@earendil-works/pi-coding-agent";
2
2
  import { type EditorComponent, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
3
3
  import type { AskUserController } from "../session/controller.ts";
4
- import type { NormalizedChoiceQuestion } from "../types.ts";
5
4
  import {
6
- formatSplitLine,
7
- padRight,
8
- pushWrappedWithPrefix,
9
- renderMiniBox,
10
- renderPrompt,
11
- safeWidth,
12
- } from "./form-render-primitives.ts";
5
+ renderChoiceScreen,
6
+ renderEditorScreen,
7
+ renderTextScreen,
8
+ } from "./form-question-render.ts";
9
+ import { formatSplitLine, padRight, renderPrompt, safeWidth } from "./form-render-primitives.ts";
13
10
  import { renderReviewScreen } from "./form-review-render.ts";
14
11
  import type { FocusTarget, FormMode } from "./form-view.ts";
15
-
12
+ import {
13
+ type FormLineRange,
14
+ type FormViewportLayout,
15
+ layoutFormViewport,
16
+ offsetFormLineRange,
17
+ type RenderedFormSection,
18
+ } from "./form-viewport.ts";
19
+
20
+ const MIN_FRAMED_WIDTH = 8;
21
+ const FRAME_HORIZONTAL_CHROME = 4;
22
+ const FRAME_BORDER_ROWS = 2;
23
+ const SCROLL_INDICATOR_ROWS = 1;
24
+ const PLAIN_SCROLL_INDICATOR_MIN_HEIGHT = 2;
25
+ const COMPACT_SCROLL_INDICATOR_WIDTH = 8;
26
+
27
+ /** Inputs required to render one form frame and its current viewport state. */
16
28
  export interface RenderFormFrameArgs {
17
29
  width: number;
30
+ maxHeight: number;
31
+ scrollOffset: number;
32
+ revealFocus: boolean;
18
33
  theme: Theme;
19
34
  controller: AskUserController;
20
35
  mode: FormMode;
@@ -27,66 +42,185 @@ export interface RenderFormFrameArgs {
27
42
  editorContext?: string;
28
43
  }
29
44
 
30
- export function renderFormFrame(args: RenderFormFrameArgs): string[] {
45
+ /** Rendered terminal lines plus the viewport state retained by the form component. */
46
+ export interface RenderedFormFrame {
47
+ lines: string[];
48
+ viewport: FormViewportLayout & { overflow: boolean };
49
+ }
50
+
51
+ /**
52
+ * Render the complete form when it fits. For overflow, keep the header fixed and
53
+ * allocate the remaining framed rows to a scrollable content window and indicator.
54
+ */
55
+ export function renderFormFrame(args: RenderFormFrameArgs): RenderedFormFrame {
31
56
  const width = safeWidth(args.width);
32
- if (width < 8) {
33
- return renderFrameContent({ ...args, width }).map((line) => truncateToWidth(line, width));
57
+ const maxHeight = Math.max(1, Math.floor(args.maxHeight));
58
+ const frameArgs = {
59
+ ...args,
60
+ width: width < MIN_FRAMED_WIDTH ? width : Math.max(1, width - FRAME_HORIZONTAL_CHROME),
61
+ };
62
+ const header = renderHeader(frameArgs);
63
+ const body = renderFrameBody(frameArgs);
64
+ const footer = [
65
+ "",
66
+ ...wrapTextWithAnsi(frameArgs.theme.fg("dim", renderFooter(frameArgs)), frameArgs.width),
67
+ ];
68
+ const scrollableContent = [...body.lines, ...footer];
69
+ const fullContent = [...header, ...scrollableContent];
70
+ const fullFocusedRange = offsetFormLineRange(body.focusedRange, header.length);
71
+ const naturalHeight = fullContent.length + (width < MIN_FRAMED_WIDTH ? 0 : FRAME_BORDER_ROWS);
72
+
73
+ if (naturalHeight <= maxHeight) {
74
+ return {
75
+ lines:
76
+ width < MIN_FRAMED_WIDTH
77
+ ? truncateLines(fullContent, width)
78
+ : frameLines(args.theme, fullContent, width),
79
+ viewport: completeViewport(body.lines),
80
+ };
34
81
  }
35
82
 
36
- const innerWidth = Math.max(1, width - 4);
37
- const content = renderFrameContent({ ...args, width: innerWidth });
38
- const border = args.theme.fg("borderAccent", "│");
39
- const top = args.theme.fg("borderAccent", `╭${"─".repeat(width - 2)}╮`);
40
- const bottom = args.theme.fg("borderAccent", `╰${"─".repeat(width - 2)}╯`);
83
+ if (width < MIN_FRAMED_WIDTH) {
84
+ const showIndicator = maxHeight >= PLAIN_SCROLL_INDICATOR_MIN_HEIGHT;
85
+ const viewport = layoutFormViewport({
86
+ lines: fullContent,
87
+ maxRows: maxHeight - (showIndicator ? 1 : 0),
88
+ scrollOffset: args.scrollOffset,
89
+ focusedRange: fullFocusedRange,
90
+ revealFocus: args.revealFocus,
91
+ });
92
+ const lines = showIndicator
93
+ ? [...viewport.lines, renderScrollIndicator(args.theme, viewport, width, scrollHint(args))]
94
+ : viewport.lines;
95
+ return {
96
+ lines: truncateLines(lines, width),
97
+ viewport: { ...viewport, overflow: true },
98
+ };
99
+ }
41
100
 
42
- return [
43
- top,
44
- ...content.map((line) => `${border} ${padRight(line, innerWidth)} ${border}`),
45
- bottom,
46
- ].map((line) => truncateToWidth(line, width));
101
+ return renderConstrainedFrame({
102
+ args: frameArgs,
103
+ width,
104
+ maxHeight,
105
+ header,
106
+ scrollableContent,
107
+ focusedRange: body.focusedRange,
108
+ fullContent,
109
+ fullFocusedRange,
110
+ });
47
111
  }
48
112
 
49
- function renderFrameContent(args: RenderFormFrameArgs): string[] {
50
- const width = safeWidth(args.width);
51
- const lines: string[] = [];
52
- lines.push(...renderHeader(args));
53
- lines.push("");
54
-
55
- if (args.mode === "review") {
56
- lines.push(...renderReviewScreen(args));
57
- } else if (isEditorMode(args.mode)) {
58
- lines.push(...renderEditorScreen(args));
59
- } else {
60
- const question = args.controller.currentQuestion;
61
- if (question.type === "text") {
62
- lines.push(...renderTextScreen(args));
63
- } else {
64
- lines.push(...renderChoiceScreen(args));
65
- }
113
+ function renderConstrainedFrame(options: {
114
+ args: RenderFormFrameArgs;
115
+ width: number;
116
+ maxHeight: number;
117
+ header: string[];
118
+ scrollableContent: string[];
119
+ focusedRange?: FormLineRange;
120
+ fullContent: string[];
121
+ fullFocusedRange?: FormLineRange;
122
+ }): RenderedFormFrame {
123
+ const { args, width, maxHeight, header, scrollableContent, focusedRange } = options;
124
+ const contentRows = maxHeight - header.length - FRAME_BORDER_ROWS - SCROLL_INDICATOR_ROWS;
125
+ if (contentRows >= 1) {
126
+ const viewport = layoutFormViewport({
127
+ lines: scrollableContent,
128
+ maxRows: contentRows,
129
+ scrollOffset: args.scrollOffset,
130
+ focusedRange,
131
+ revealFocus: args.revealFocus,
132
+ });
133
+ const content = [
134
+ ...header,
135
+ ...viewport.lines,
136
+ renderScrollIndicator(args.theme, viewport, args.width, scrollHint(args)),
137
+ ];
138
+ return {
139
+ lines: frameLines(args.theme, content, width),
140
+ viewport: { ...viewport, overflow: true },
141
+ };
66
142
  }
67
143
 
68
- lines.push("");
69
- lines.push(...wrapTextWithAnsi(args.theme.fg("dim", renderFooter(args)), width));
70
- return lines.map((line) => truncateToWidth(line, width));
144
+ return renderTinyFrame(options);
71
145
  }
72
146
 
73
- function renderHeader(args: RenderFormFrameArgs): string[] {
74
- const lines: string[] = [];
75
- const { intro, title } = args.controller.questionnaire;
76
- const titleText = args.theme.fg("accent", args.theme.bold(title ?? "ask_user"));
77
- const contextText = args.theme.fg("muted", headerContext(args));
147
+ function renderTinyFrame(options: {
148
+ args: RenderFormFrameArgs;
149
+ width: number;
150
+ maxHeight: number;
151
+ fullContent: string[];
152
+ fullFocusedRange?: FormLineRange;
153
+ }): RenderedFormFrame {
154
+ const { args, width, maxHeight, fullContent, fullFocusedRange } = options;
155
+ if (maxHeight <= FRAME_BORDER_ROWS) {
156
+ const viewport = layoutFormViewport({
157
+ lines: fullContent,
158
+ maxRows: maxHeight,
159
+ scrollOffset: args.scrollOffset,
160
+ focusedRange: fullFocusedRange,
161
+ revealFocus: args.revealFocus,
162
+ });
163
+ return {
164
+ lines: truncateLines(viewport.lines, width),
165
+ viewport: { ...viewport, overflow: true },
166
+ };
167
+ }
78
168
 
79
- lines.push(formatSplitLine(titleText, contextText, args.width));
80
- lines.push(renderProgressLine(args));
169
+ const showIndicator = maxHeight >= FRAME_BORDER_ROWS + SCROLL_INDICATOR_ROWS + 1;
170
+ const viewport = layoutFormViewport({
171
+ lines: fullContent,
172
+ maxRows: maxHeight - FRAME_BORDER_ROWS - (showIndicator ? SCROLL_INDICATOR_ROWS : 0),
173
+ scrollOffset: args.scrollOffset,
174
+ focusedRange: fullFocusedRange,
175
+ revealFocus: args.revealFocus,
176
+ });
177
+ const content = showIndicator
178
+ ? [
179
+ ...viewport.lines,
180
+ renderScrollIndicator(
181
+ args.theme,
182
+ viewport,
183
+ Math.max(1, width - FRAME_HORIZONTAL_CHROME),
184
+ scrollHint(args),
185
+ ),
186
+ ]
187
+ : viewport.lines;
188
+ return {
189
+ lines: frameLines(args.theme, content, width),
190
+ viewport: { ...viewport, overflow: true },
191
+ };
192
+ }
81
193
 
194
+ function renderFrameBody(args: RenderFormFrameArgs): RenderedFormSection {
195
+ const lines: string[] = [];
196
+ const { intro } = args.controller.questionnaire;
82
197
  if (intro) {
83
198
  lines.push("");
84
199
  lines.push(...renderPrompt(intro, args.width));
85
200
  lines.push("");
86
201
  lines.push(args.theme.fg("borderMuted", "─".repeat(args.width)));
87
202
  }
203
+ lines.push("");
204
+
205
+ const section = renderActiveScreen(args);
206
+ const focusedRange = offsetFormLineRange(section.focusedRange, lines.length);
207
+ lines.push(...section.lines);
208
+ return { lines, focusedRange };
209
+ }
88
210
 
89
- return lines;
211
+ function renderActiveScreen(args: RenderFormFrameArgs): RenderedFormSection {
212
+ if (args.mode === "review") return renderReviewScreen(args);
213
+ if (isEditorMode(args.mode)) return renderEditorScreen(args);
214
+ return args.controller.currentQuestion.type === "text"
215
+ ? renderTextScreen(args)
216
+ : renderChoiceScreen(args);
217
+ }
218
+
219
+ function renderHeader(args: RenderFormFrameArgs): string[] {
220
+ const { title } = args.controller.questionnaire;
221
+ const titleText = args.theme.fg("accent", args.theme.bold(title ?? "ask_user"));
222
+ const contextText = args.theme.fg("muted", headerContext(args));
223
+ return [formatSplitLine(titleText, contextText, args.width), renderProgressLine(args)];
90
224
  }
91
225
 
92
226
  function headerContext(args: RenderFormFrameArgs): string {
@@ -117,148 +251,60 @@ function renderProgressLine(args: RenderFormFrameArgs): string {
117
251
  return truncateToWidth(`${args.theme.fg("dim", label)} ${segments}`, args.width);
118
252
  }
119
253
 
120
- function renderChoiceScreen(args: RenderFormFrameArgs): string[] {
121
- const lines: string[] = [];
122
- const question = args.controller.currentQuestion;
123
-
124
- if (question.type !== "choice") return lines;
125
-
126
- lines.push(...renderPrompt(question.prompt, args.width));
127
- if (args.controller.isQuestionMarkedUnanswered(question.id)) {
128
- lines.push("");
129
- lines.push(args.theme.fg("warning", "Marked unanswered; comments preserved."));
130
- }
131
- lines.push("");
132
-
133
- if (args.detailsText && args.width >= 80) {
134
- lines.push(...renderChoiceWithDetails(args, question));
135
- return lines;
136
- }
137
-
138
- for (let i = 0; i < question.options.length; i += 1) {
139
- lines.push(...renderChoiceOptionLines(args, question, i, args.width));
140
- }
141
-
142
- if (args.detailsText) {
143
- lines.push("");
144
- lines.push(...renderDetailsCard(args.theme, args.detailsText, args.width));
145
- }
146
-
147
- return lines;
148
- }
149
-
150
- function renderChoiceWithDetails(
151
- args: RenderFormFrameArgs,
152
- question: NormalizedChoiceQuestion,
153
- ): string[] {
154
- const gap = 2;
155
- const divider = args.theme.fg("borderMuted", "│");
156
- const dividerWidth = 1;
157
- const minLeftWidth = 28;
158
- const preferredDetailsWidth = Math.max(30, Math.floor(args.width * 0.38));
159
- const rightWidth = Math.max(
160
- 22,
161
- Math.min(preferredDetailsWidth, args.width - gap - dividerWidth - gap - minLeftWidth),
162
- );
163
- const leftWidth = Math.max(1, args.width - gap - dividerWidth - gap - rightWidth);
164
-
165
- const optionLines: string[] = [];
166
- for (let i = 0; i < question.options.length; i += 1) {
167
- optionLines.push(...renderChoiceOptionLines(args, question, i, leftWidth));
168
- }
169
-
170
- const detailsLines = renderDetailsCard(args.theme, args.detailsText ?? "", rightWidth);
171
-
172
- const merged: string[] = [];
173
- const maxRows = Math.max(optionLines.length, detailsLines.length);
174
- for (let i = 0; i < maxRows; i += 1) {
175
- const left = optionLines[i] ?? "";
176
- const right = detailsLines[i] ?? "";
177
- const mergedLine = `${padRight(left, leftWidth)}${" ".repeat(gap)}${divider}${" ".repeat(gap)}${right}`;
178
- merged.push(truncateToWidth(mergedLine, args.width));
179
- }
180
-
181
- return merged;
182
- }
183
-
184
- function renderChoiceOptionLines(
185
- args: RenderFormFrameArgs,
186
- question: NormalizedChoiceQuestion,
187
- optionIndex: number,
188
- width: number,
189
- ): string[] {
190
- const lines: string[] = [];
191
- const opt = question.options[optionIndex];
192
- const focused = optionIndex === args.choiceFocusIndex;
193
- const selected = args.controller.isOptionSelected(question.id, opt.value);
194
- const hasComment = !!args.controller.getOptionComment(question.id, opt.value);
195
-
196
- const marker = choiceMarker(question.multi, selected);
197
- const isRecommended = question.recommendedIndexes.includes(optionIndex);
198
- const prefix = focused ? " → " : " ";
199
- const label = `${marker} ${opt.label}${isRecommended ? " [recommended]" : ""}${hasComment ? " [comment]" : ""}`;
200
- pushWrappedWithPrefix({
254
+ function completeViewport(lines: string[]): FormViewportLayout & { overflow: false } {
255
+ return {
201
256
  lines,
202
- prefix,
203
- text: focused ? args.theme.fg("accent", label) : label,
204
- width,
205
- });
206
-
207
- if (opt.description) {
208
- pushWrappedWithPrefix({
209
- lines,
210
- prefix: " ",
211
- text: args.theme.fg("muted", opt.description),
212
- width,
213
- });
214
- }
215
-
216
- return lines;
257
+ scrollOffset: 0,
258
+ maxScrollOffset: 0,
259
+ pageSize: Math.max(1, lines.length),
260
+ hiddenAbove: 0,
261
+ hiddenBelow: 0,
262
+ overflow: false,
263
+ };
217
264
  }
218
265
 
219
- function choiceMarker(multi: boolean, selected: boolean): string {
220
- if (multi) return selected ? "[x]" : "[ ]";
221
- return selected ? "(*)" : "( )";
266
+ function renderScrollIndicator(
267
+ theme: Theme,
268
+ viewport: FormViewportLayout,
269
+ width: number,
270
+ hint: string,
271
+ ): string {
272
+ const first = viewport.scrollOffset + 1;
273
+ const last = viewport.scrollOffset + viewport.lines.length;
274
+ const above = viewport.hiddenAbove > 0 ? "↑" : "·";
275
+ const below = viewport.hiddenBelow > 0 ? "↓" : "·";
276
+ const text =
277
+ width < COMPACT_SCROLL_INDICATOR_WIDTH
278
+ ? `${above} ${below}`
279
+ : width < 20
280
+ ? `${above}${viewport.hiddenAbove} ${below}${viewport.hiddenBelow}`
281
+ : `${above}${viewport.hiddenAbove} ${first}-${last}/${last + viewport.hiddenBelow} ${hint} scroll ${below}${viewport.hiddenBelow}`;
282
+ return truncateToWidth(theme.fg("dim", text), width, "");
222
283
  }
223
284
 
224
- function renderTextScreen(args: RenderFormFrameArgs): string[] {
225
- const lines: string[] = [];
226
- const question = args.controller.currentQuestion;
227
-
228
- if (question.type !== "text") return lines;
229
-
230
- lines.push(...renderPrompt(question.prompt, args.width));
231
- lines.push("");
232
- lines.push(args.theme.fg("accent", "Your answer"));
233
- lines.push(...args.editor.render(safeWidth(args.width)));
234
-
235
- if (question.placeholder && !args.editor.getText()) {
236
- lines.push("");
237
- lines.push(
238
- ...wrapTextWithAnsi(args.theme.fg("dim", `Placeholder: ${question.placeholder}`), args.width),
239
- );
240
- }
241
-
242
- return lines;
285
+ function scrollHint(args: RenderFormFrameArgs): string {
286
+ return args.focus === "editor" ? "Alt+PgUp/PgDn" : "PgUp/PgDn";
243
287
  }
244
288
 
245
- function renderEditorScreen(args: RenderFormFrameArgs): string[] {
246
- const lines: string[] = [];
247
- const label = args.editorLabel ?? "Editor";
248
- const title = args.editorContext ? `${label}: ${args.editorContext}` : label;
249
- lines.push(args.theme.fg("accent", title));
250
- lines.push(...args.editor.render(safeWidth(args.width)));
251
- return lines;
289
+ function frameLines(theme: Theme, content: string[], width: number): string[] {
290
+ const innerWidth = Math.max(1, width - FRAME_HORIZONTAL_CHROME);
291
+ const border = theme.fg("borderAccent", "│");
292
+ const top = theme.fg("borderAccent", `╭${"─".repeat(width - 2)}╮`);
293
+ const bottom = theme.fg("borderAccent", `╰${"─".repeat(width - 2)}╯`);
294
+ return [
295
+ top,
296
+ ...content.map((line) => `${border} ${padRight(line, innerWidth)} ${border}`),
297
+ bottom,
298
+ ].map((line) => truncateToWidth(line, width));
252
299
  }
253
300
 
254
- function renderDetailsCard(theme: Theme, detailsText: string, width: number): string[] {
255
- const innerWidth = Math.max(1, safeWidth(width) - 4);
256
- return renderMiniBox(theme, "Details", renderPrompt(detailsText, innerWidth), width);
301
+ function truncateLines(lines: string[], width: number): string[] {
302
+ return lines.map((line) => truncateToWidth(line, width));
257
303
  }
258
304
 
259
305
  function renderFooter(args: RenderFormFrameArgs): string {
260
306
  if (args.mode === "review") {
261
- return "Keys: ↑↓ move · Enter edit/submit · c form comment · ←/Shift+Tab back · Esc cancel";
307
+ return "Keys: ↑↓ move/edge scroll · Enter edit/submit · c form comment · ←/Shift+Tab back · Esc cancel";
262
308
  }
263
309
 
264
310
  if (isEditorMode(args.mode)) {
@@ -272,10 +318,10 @@ function renderFooter(args: RenderFormFrameArgs): string {
272
318
  }
273
319
 
274
320
  if (question.multi) {
275
- return "Keys: ↑↓ move · Space toggle · Enter accept · c question comment · n option comment · u unanswered · ←/→ or Tab/Shift+Tab · Esc cancel";
321
+ return "Keys: ↑↓ move/edge scroll · Space toggle · Enter accept · c question comment · n option comment · u unanswered · ←/→ or Tab/Shift+Tab · Esc cancel";
276
322
  }
277
323
 
278
- return "Keys: ↑↓ move · Space select · Enter select · c question comment · n option comment · u unanswered · ←/→ or Tab/Shift+Tab · Esc cancel";
324
+ return "Keys: ↑↓ move/edge scroll · Space select · Enter select · c question comment · n option comment · u unanswered · ←/→ or Tab/Shift+Tab · Esc cancel";
279
325
  }
280
326
 
281
327
  function isEditorMode(mode: FormMode): boolean {
@@ -8,12 +8,14 @@ import {
8
8
  safeWidth,
9
9
  wrapLines,
10
10
  } from "./form-render-primitives.ts";
11
+ import type { FormLineRange, RenderedFormSection } from "./form-viewport.ts";
11
12
 
12
- export function renderReviewScreen(args: RenderFormFrameArgs): string[] {
13
+ export function renderReviewScreen(args: RenderFormFrameArgs): RenderedFormSection {
13
14
  const lines: string[] = [];
14
15
  const outcome = args.controller.outcome();
15
16
  const questionCount = args.controller.questionnaire.questions.length;
16
17
  const submitIndex = questionCount;
18
+ let focusedRange: FormLineRange | undefined;
17
19
 
18
20
  lines.push(args.theme.fg("accent", "Review your answers"));
19
21
  lines.push(
@@ -24,7 +26,10 @@ export function renderReviewScreen(args: RenderFormFrameArgs): string[] {
24
26
  for (let i = 0; i < outcome.responses.length; i += 1) {
25
27
  const resp = outcome.responses[i];
26
28
  const question = args.controller.questionnaire.questions[i];
27
- lines.push(...renderReviewQuestionCard(args, question, resp, i === args.reviewFocusIndex));
29
+ const focused = i === args.reviewFocusIndex;
30
+ const start = lines.length;
31
+ lines.push(...renderReviewQuestionCard(args, question, resp, focused));
32
+ if (focused) focusedRange = { start, end: lines.length };
28
33
  }
29
34
 
30
35
  if (outcome.comment) {
@@ -33,9 +38,12 @@ export function renderReviewScreen(args: RenderFormFrameArgs): string[] {
33
38
  }
34
39
 
35
40
  lines.push("");
36
- lines.push(...renderSubmitCard(args, args.reviewFocusIndex === submitIndex));
41
+ const submitFocused = args.reviewFocusIndex === submitIndex;
42
+ const submitStart = lines.length;
43
+ lines.push(...renderSubmitCard(args, submitFocused));
44
+ if (submitFocused) focusedRange = { start: submitStart, end: lines.length };
37
45
 
38
- return lines;
46
+ return { lines, focusedRange };
39
47
  }
40
48
 
41
49
  function renderReviewQuestionCard(
@@ -0,0 +1,92 @@
1
+ /** Maximum number of terminal rows used by the inline Ask User form. */
2
+ const MAX_FORM_HEIGHT = 24;
3
+ const TERMINAL_HEIGHT_SHARE = 0.7;
4
+
5
+ /** A zero-based, end-exclusive range in rendered form content. */
6
+ export interface FormLineRange {
7
+ start: number;
8
+ end: number;
9
+ }
10
+
11
+ /** Rendered lines with an optional range that must remain visible during navigation. */
12
+ export interface RenderedFormSection {
13
+ lines: string[];
14
+ focusedRange?: FormLineRange;
15
+ }
16
+
17
+ /** The visible window and scroll limits calculated for one rendered form document. */
18
+ export interface FormViewportLayout {
19
+ lines: string[];
20
+ scrollOffset: number;
21
+ maxScrollOffset: number;
22
+ pageSize: number;
23
+ hiddenAbove: number;
24
+ hiddenBelow: number;
25
+ }
26
+
27
+ /**
28
+ * Calculate a conservative inline height that leaves room for Pi's transcript and footer.
29
+ * The absolute cap keeps the form stable on large terminals, while the terminal share
30
+ * keeps it usable on small terminals.
31
+ */
32
+ export function calculateFormHeightLimit(terminalRows: number): number {
33
+ const rows = Math.max(1, Math.floor(terminalRows));
34
+ const proportional = Math.max(1, Math.floor(rows * TERMINAL_HEIGHT_SHARE));
35
+ return Math.min(rows, MAX_FORM_HEIGHT, proportional);
36
+ }
37
+
38
+ /** Offset a rendered line range while preserving its end-exclusive shape. */
39
+ export function offsetFormLineRange(
40
+ range: FormLineRange | undefined,
41
+ offset: number,
42
+ ): FormLineRange | undefined {
43
+ return range ? { start: range.start + offset, end: range.end + offset } : undefined;
44
+ }
45
+
46
+ /**
47
+ * Return one visible content window. The module has no knowledge of question or form state.
48
+ */
49
+ export function layoutFormViewport(args: {
50
+ lines: string[];
51
+ maxRows: number;
52
+ scrollOffset: number;
53
+ focusedRange?: FormLineRange;
54
+ revealFocus: boolean;
55
+ }): FormViewportLayout {
56
+ const pageSize = Math.max(1, Math.floor(args.maxRows));
57
+ const maxScrollOffset = Math.max(0, args.lines.length - pageSize);
58
+ let scrollOffset = clamp(Math.floor(args.scrollOffset), 0, maxScrollOffset);
59
+
60
+ if (args.revealFocus && args.focusedRange) {
61
+ const focusedStart = clamp(args.focusedRange.start, 0, Math.max(0, args.lines.length - 1));
62
+ const focusedEnd = clamp(
63
+ Math.max(focusedStart + 1, args.focusedRange.end),
64
+ focusedStart + 1,
65
+ args.lines.length,
66
+ );
67
+ const focusedHeight = focusedEnd - focusedStart;
68
+
69
+ if (focusedHeight >= pageSize) {
70
+ scrollOffset = focusedStart;
71
+ } else if (focusedStart < scrollOffset) {
72
+ scrollOffset = focusedStart;
73
+ } else if (focusedEnd > scrollOffset + pageSize) {
74
+ scrollOffset = focusedEnd - pageSize;
75
+ }
76
+ scrollOffset = clamp(scrollOffset, 0, maxScrollOffset);
77
+ }
78
+
79
+ const end = Math.min(args.lines.length, scrollOffset + pageSize);
80
+ return {
81
+ lines: args.lines.slice(scrollOffset, end),
82
+ scrollOffset,
83
+ maxScrollOffset,
84
+ pageSize,
85
+ hiddenAbove: scrollOffset,
86
+ hiddenBelow: Math.max(0, args.lines.length - end),
87
+ };
88
+ }
89
+
90
+ function clamp(value: number, min: number, max: number): number {
91
+ return Math.max(min, Math.min(max, value));
92
+ }