@mrclrchtr/supi-ask-user 4.9.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.
@@ -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
+ }