@lune_99/pi-ask-question 0.0.0-stage → 0.1.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,813 @@
1
+ /**
2
+ * Terminal renderer of the question panel: frame, header/footer hints, the focused question,
3
+ * its option rows, the submit summary and the option preview pane.
4
+ *
5
+ * It reads the request's `questions` and `draft` but never mutates them; the panel owns the
6
+ * interaction, the draft and the editor, and hands the renderer the transient state it cannot
7
+ * read from the request (`inputMode`, the editor component and the body budget).
8
+ *
9
+ * The renderer's own caches are render state, not session state: the Markdown parser and one
10
+ * preview renderer per question, both dropped by `invalidate()` when the theme changes.
11
+ */
12
+ import {
13
+ getMarkdownTheme,
14
+ type Theme,
15
+ type ThemeColor,
16
+ } from "@earendil-works/pi-coding-agent";
17
+ import {
18
+ CURSOR_MARKER,
19
+ Markdown,
20
+ truncateToWidth,
21
+ visibleWidth,
22
+ wrapTextWithAnsi,
23
+ } from "@earendil-works/pi-tui";
24
+
25
+ import {
26
+ formatAnswer,
27
+ questionHeaderPrefix,
28
+ questionTabLabel,
29
+ summarizeText,
30
+ } from "../../core/question-format.ts";
31
+ import type {
32
+ AskQuestion,
33
+ AskQuestionAnswer,
34
+ AskQuestionRequest,
35
+ } from "../../core/question-types.ts";
36
+ import {
37
+ MIN_BLOCK_ROWS,
38
+ STACKED_GAP_ROWS,
39
+ decidePreviewLayout,
40
+ leftColumnWidth,
41
+ previewBlockRowBudget,
42
+ previewColumnWidths,
43
+ } from "../preview/preview-layout.ts";
44
+ import { QuestionPreviewRenderer } from "../preview/preview-renderer.ts";
45
+ import {
46
+ areAllAnswered,
47
+ focusedRowIndex,
48
+ questionRows,
49
+ type QuestionRow,
50
+ } from "./question-panel-controller.ts";
51
+
52
+ /** Minimum inner width so the frame math never produces negative repeat counts. */
53
+ const PANEL_MIN_INNER_WIDTH = 20;
54
+ /** Top border, header and the separator above the body. */
55
+ const BODY_TOP = 3;
56
+ /** Left border plus the cell's leading space. */
57
+ const CONTENT_LEFT = 2;
58
+ /** The editor is drawn one column in from the content edge. */
59
+ const EDITOR_INSET = 1;
60
+
61
+ /** The editor while it owns the keys: only its rendered lines are needed here. */
62
+ export interface QuestionPanelEditor {
63
+ render(width: number): string[];
64
+ }
65
+
66
+ export interface QuestionPanelRenderState {
67
+ /** True while the editor owns the keys; the footer and the preview column read it. */
68
+ inputMode: boolean;
69
+ /** Body row budget the overlay grants this render. */
70
+ maxBodyHeight: number;
71
+ /** Editor to draw below the options; absent unless `inputMode` is set. */
72
+ editor?: QuestionPanelEditor;
73
+ /** First body row to show; `undefined` keeps the focused row centered. */
74
+ bodyScroll?: number;
75
+ /** First preview content row to show. */
76
+ previewScroll?: number;
77
+ }
78
+
79
+ /** Panel-local column span `[start, end)` on one row. */
80
+ export interface PanelSpan {
81
+ y: number;
82
+ start: number;
83
+ end: number;
84
+ }
85
+
86
+ /** Panel-local rectangle; `x`/`y` is the top-left cell. */
87
+ export interface PanelRect {
88
+ x: number;
89
+ y: number;
90
+ width: number;
91
+ height: number;
92
+ }
93
+
94
+ export type TabTarget = { kind: "tab"; index: number } | { kind: "step"; step: number };
95
+
96
+ /**
97
+ * Where the last frame put each interactive element. Mouse events arrive in overlay-local
98
+ * cells, so hit-testing has to use the geometry the user actually sees.
99
+ */
100
+ export interface QuestionPanelLayout {
101
+ tabs: Array<PanelSpan & { target: TabTarget }>;
102
+ body: PanelRect & { offset: number; maxOffset: number };
103
+ preview?: PanelRect & { offset: number; maxOffset: number };
104
+ /** The editor's full extent, `y` possibly outside the body window when it is scrolled. */
105
+ editor?: PanelRect;
106
+ }
107
+
108
+ export interface QuestionPanelFrame {
109
+ lines: string[];
110
+ layout: QuestionPanelLayout;
111
+ }
112
+
113
+ /** Body-relative positions collected while the body is built. */
114
+ interface BodyMarks {
115
+ preview?: { line: number; height: number; start: number; width: number; offset: number; maxOffset: number };
116
+ editor?: { line: number; height: number; width: number };
117
+ }
118
+
119
+ interface RenderedBody {
120
+ lines: string[];
121
+ focusLine: number;
122
+ marks: BodyMarks;
123
+ /**
124
+ * Body rows the window has to hold while the editor owns the keys. Content above scrolls
125
+ * away instead of the input box being clipped at the panel's bottom edge.
126
+ */
127
+ keep?: { top: number; bottom: number; cursor: number };
128
+ }
129
+
130
+ export interface QuestionPanelRendererOptions {
131
+ request: AskQuestionRequest;
132
+ theme: Theme;
133
+ }
134
+
135
+ export class QuestionPanelRenderer {
136
+ private readonly request: AskQuestionRequest;
137
+ private readonly theme: Theme;
138
+
139
+ private markdown: Markdown | undefined;
140
+ private markdownText: string | undefined;
141
+ /**
142
+ * One preview renderer per question: an option index only identifies an option inside its
143
+ * own question, so a renderer must not be shared across tabs.
144
+ */
145
+ private readonly previewRenderers = new Map<number, QuestionPreviewRenderer>();
146
+
147
+ constructor(options: QuestionPanelRendererOptions) {
148
+ this.request = options.request;
149
+ this.theme = options.theme;
150
+ }
151
+
152
+ render(width: number, state: QuestionPanelRenderState): QuestionPanelFrame {
153
+ const innerWidth = Math.max(PANEL_MIN_INNER_WIDTH, width - 2);
154
+ const contentWidth = innerWidth - 2;
155
+ // The tab strip stays put while the body scrolls. It is the only way to see which
156
+ // questions exist and to reach the others, so it must not scroll out of view.
157
+ const tabs = this.isMultiQuestion
158
+ ? this.renderTabsBlock(contentWidth)
159
+ : { lines: [], spans: [] };
160
+ const bodyRoom = Math.max(1, state.maxBodyHeight - tabs.lines.length);
161
+ const body = this.renderBody(contentWidth, bodyRoom, state);
162
+ const bodyHeight = Math.min(body.lines.length, bodyRoom);
163
+ const window = bodyWindow(
164
+ body.lines.length,
165
+ body.focusLine,
166
+ bodyHeight,
167
+ state.bodyScroll,
168
+ body.keep,
169
+ );
170
+ const visible = [...tabs.lines, ...body.lines.slice(window.offset, window.offset + bodyHeight)];
171
+
172
+ while (visible.length < tabs.lines.length + bodyHeight) {
173
+ visible.push("");
174
+ }
175
+
176
+ const layout = this.layoutFor(tabs.spans, body.marks, {
177
+ x: CONTENT_LEFT,
178
+ y: BODY_TOP + tabs.lines.length,
179
+ width: contentWidth,
180
+ height: bodyHeight,
181
+ ...window,
182
+ });
183
+
184
+ const lines = [
185
+ this.frame(`┌${"─".repeat(innerWidth)}┐`),
186
+ this.frame("│") + this.renderHeader(innerWidth) + this.frame("│"),
187
+ this.frame(`├${"─".repeat(innerWidth)}┤`),
188
+ ...visible.map((line) => this.frame("│") + this.cell(line, innerWidth) + this.frame("│")),
189
+ this.frame(`├${"─".repeat(innerWidth)}┤`),
190
+ this.frame("│") + this.renderFooter(innerWidth, state.inputMode) + this.frame("│"),
191
+ this.frame(`└${"─".repeat(innerWidth)}┘`),
192
+ ];
193
+
194
+ return { lines, layout };
195
+ }
196
+
197
+ /** Moves the body-relative marks into panel coordinates, keeping only what is on screen. */
198
+ private layoutFor(
199
+ tabs: QuestionPanelLayout["tabs"],
200
+ marks: BodyMarks,
201
+ body: QuestionPanelLayout["body"],
202
+ ): QuestionPanelLayout {
203
+ const toPanel = (line: number) => body.y + line - body.offset;
204
+
205
+ const layout: QuestionPanelLayout = { tabs, body };
206
+
207
+ if (marks.preview) {
208
+ const top = Math.max(marks.preview.line, body.offset);
209
+ const bottom = Math.min(marks.preview.line + marks.preview.height, body.offset + body.height);
210
+
211
+ if (bottom > top) {
212
+ layout.preview = {
213
+ x: body.x + marks.preview.start,
214
+ y: toPanel(top),
215
+ width: marks.preview.width,
216
+ height: bottom - top,
217
+ offset: marks.preview.offset,
218
+ maxOffset: marks.preview.maxOffset,
219
+ };
220
+ }
221
+ }
222
+
223
+ if (marks.editor) {
224
+ layout.editor = {
225
+ x: body.x + EDITOR_INSET,
226
+ y: toPanel(marks.editor.line),
227
+ width: marks.editor.width,
228
+ height: marks.editor.height,
229
+ };
230
+ }
231
+
232
+ return layout;
233
+ }
234
+
235
+ invalidate(): void {
236
+ this.markdown = undefined;
237
+ this.markdownText = undefined;
238
+ // The renderers hold the markdown theme they were built with, so a theme change has
239
+ // to rebuild them.
240
+ this.previewRenderers.clear();
241
+ }
242
+
243
+ private get draft() {
244
+ return this.request.draft;
245
+ }
246
+
247
+ private get questions(): readonly AskQuestion[] {
248
+ return this.request.questions;
249
+ }
250
+
251
+ private get isMultiQuestion(): boolean {
252
+ return this.questions.length > 1;
253
+ }
254
+
255
+ private get isSubmitTab(): boolean {
256
+ return this.draft.currentIndex >= this.questions.length;
257
+ }
258
+
259
+ private currentQuestion(): AskQuestion | undefined {
260
+ return this.questions[this.draft.currentIndex];
261
+ }
262
+
263
+ private allAnswered(): boolean {
264
+ return areAllAnswered(this.questions, this.draft);
265
+ }
266
+
267
+ private renderHeader(width: number): string {
268
+ const contentWidth = width - 2;
269
+ const title = this.theme.bold("Questions");
270
+ const answered = this.draft.answers.filter((answer) => answer !== undefined).length;
271
+ const status = `${answered}/${this.questions.length} answered`;
272
+ const gap = Math.max(1, contentWidth - visibleWidth(title) - visibleWidth(status));
273
+
274
+ return this.cell(`${title}${" ".repeat(gap)}${this.theme.fg("muted", status)}`, width);
275
+ }
276
+
277
+ private renderFooter(width: number, inputMode: boolean): string {
278
+ const question = this.currentQuestion();
279
+
280
+ let hints: string;
281
+
282
+ if (inputMode) {
283
+ // Shift+S belongs to the editor while it owns the keys, so the footer must not
284
+ // advertise skip here; Esc leaves the editor and skips from the options.
285
+ hints = "Enter submit · Esc back to options";
286
+ } else if (this.isSubmitTab) {
287
+ hints = `${this.isMultiQuestion ? "Tab/←→ switch · " : ""}Enter submit · ⇧S skip · Esc close`;
288
+ } else if (question?.multiSelect === true) {
289
+ hints = "↑↓ move · Space/Enter toggle · Tab next · ⇧S skip · Esc close";
290
+ } else {
291
+ hints = `↑↓ select · Enter confirm${this.isMultiQuestion ? " · Tab/←→ switch" : ""} · ⇧S skip · Esc close`;
292
+ }
293
+
294
+ return this.cell(this.theme.fg("dim", hints), width);
295
+ }
296
+
297
+ private renderBody(
298
+ contentWidth: number,
299
+ maxBodyHeight: number,
300
+ state: QuestionPanelRenderState,
301
+ ): RenderedBody {
302
+ const lines: string[] = [];
303
+ const marks: BodyMarks = {};
304
+ let keep: RenderedBody["keep"];
305
+
306
+ if (this.isSubmitTab) {
307
+ lines.push(...this.renderSubmit(contentWidth));
308
+
309
+ return { lines, focusLine: 0, marks };
310
+ }
311
+
312
+ const question = this.currentQuestion();
313
+
314
+ if (!question) {
315
+ return { lines, focusLine: 0, marks };
316
+ }
317
+
318
+ // One question needs no label at all: the tab strip is what names the questions, and
319
+ // the question text already says what is being asked.
320
+ pushWrapped(
321
+ lines,
322
+ contentWidth,
323
+ "",
324
+ this.theme.fg("text", this.theme.bold(question.question)),
325
+ );
326
+
327
+ if (question.displayText) {
328
+ lines.push("");
329
+
330
+ for (const line of this.markdownFor(question.displayText).render(contentWidth)) {
331
+ lines.push(line);
332
+ }
333
+ }
334
+
335
+ lines.push("");
336
+
337
+ const region = this.renderQuestionRegion(
338
+ question,
339
+ contentWidth,
340
+ lines.length,
341
+ maxBodyHeight,
342
+ state.inputMode,
343
+ state.previewScroll ?? 0,
344
+ );
345
+ const regionTop = lines.length;
346
+ const focusLine = regionTop + region.focusLine;
347
+ lines.push(...region.lines);
348
+
349
+ if (region.preview) {
350
+ marks.preview = { ...region.preview, line: regionTop + region.preview.line };
351
+ }
352
+
353
+ if (state.inputMode && state.editor) {
354
+ lines.push("");
355
+ pushWrapped(lines, contentWidth, " ", this.theme.fg("muted", "Your answer:"));
356
+
357
+ // The editor draws its own frame; one column keeps it inside the panel border.
358
+ const editorWidth = Math.max(1, contentWidth - 2);
359
+ const editorLines = state.editor.render(editorWidth);
360
+ const cursor = editorLines.findIndex((line) => line.includes(CURSOR_MARKER));
361
+
362
+ marks.editor = { line: lines.length, height: editorLines.length, width: editorWidth };
363
+
364
+ for (const line of editorLines) {
365
+ lines.push(truncateToWidth(`${" ".repeat(EDITOR_INSET)}${line}`, contentWidth, "…", true));
366
+ }
367
+
368
+ lines.push("");
369
+ pushWrapped(lines, contentWidth, " ", this.theme.fg("dim", "Enter to submit · Esc to go back"));
370
+
371
+ // The editor owns the keys, so the window follows it instead of the focused option
372
+ // row: the frame and the submit hint stay whole, and only the rows above scroll.
373
+ keep = {
374
+ top: marks.editor.line,
375
+ bottom: lines.length - 1,
376
+ cursor: marks.editor.line + (cursor >= 0 ? cursor : editorLines.length - 1),
377
+ };
378
+ }
379
+
380
+ return { lines, focusLine, marks, keep };
381
+ }
382
+
383
+ /**
384
+ * The option rows, plus the preview pane when the question has one and the width allows it.
385
+ *
386
+ * `rowsAboveRegion` counts the full-width body rows already rendered above; the preview
387
+ * block is capped to what the window has left, because a block that overflows it would be
388
+ * clipped at the bottom and lose its border.
389
+ *
390
+ * The returned `focusLine` and marks are relative to the returned lines, so the caller can
391
+ * offset them against the full-width body above.
392
+ */
393
+ private renderQuestionRegion(
394
+ question: AskQuestion,
395
+ contentWidth: number,
396
+ rowsAboveRegion: number,
397
+ maxBodyHeight: number,
398
+ inputMode: boolean,
399
+ previewScroll: number,
400
+ ): OptionRegion {
401
+ const renderer = this.previewRendererFor(this.draft.currentIndex, question);
402
+
403
+ // While the editor is open the focused row is the custom row, which has no preview of
404
+ // its own, and the editor below needs the full width more than a preview does.
405
+ if (inputMode || !renderer.hasAnyPreview()) {
406
+ return this.renderOptionRows(question, contentWidth);
407
+ }
408
+
409
+ const leftWidth = leftColumnWidth(this.questions, contentWidth);
410
+ const mode = decidePreviewLayout(contentWidth, leftWidth);
411
+ const columns = previewColumnWidths(contentWidth, leftWidth, mode);
412
+ const rows = this.renderOptionRows(question, columns.leftWidth);
413
+ const stackedGap = mode === "stacked" ? STACKED_GAP_ROWS : 0;
414
+ const rowsAboveBlock = rowsAboveRegion
415
+ + (mode === "stacked" ? rows.lines.length + stackedGap : 0);
416
+ const available = maxBodyHeight - rowsAboveBlock;
417
+
418
+ // Too little room left for even a bordered placeholder: the option list keeps the full
419
+ // width instead of showing a clipped box.
420
+ if (available < MIN_BLOCK_ROWS) {
421
+ return this.renderOptionRows(question, contentWidth);
422
+ }
423
+
424
+ const block = renderer.render(
425
+ this.draft.optionIndex,
426
+ columns.rightWidth,
427
+ previewBlockRowBudget(mode, available),
428
+ previewScroll,
429
+ );
430
+ const scroll = { offset: block.offset, maxOffset: block.maxOffset };
431
+
432
+ if (mode === "stacked") {
433
+ return {
434
+ lines: [...rows.lines, ...Array<string>(stackedGap).fill(""), ...block.lines],
435
+ focusLine: rows.focusLine,
436
+ preview: {
437
+ line: rows.lines.length + stackedGap,
438
+ height: block.lines.length,
439
+ start: 0,
440
+ width: contentWidth,
441
+ ...scroll,
442
+ },
443
+ };
444
+ }
445
+
446
+ const previewStart = columns.leftWidth + columns.gap;
447
+
448
+ return {
449
+ ...composeColumns(rows, block.lines, columns, contentWidth),
450
+ preview: {
451
+ line: 0,
452
+ height: block.lines.length,
453
+ start: previewStart,
454
+ width: contentWidth - previewStart,
455
+ ...scroll,
456
+ },
457
+ };
458
+ }
459
+
460
+ /** One option row block, wrapped to `contentWidth`. */
461
+ private renderOptionRows(question: AskQuestion, contentWidth: number): OptionRegion {
462
+ const lines: string[] = [];
463
+ const rows = questionRows(question);
464
+ const focusedIndex = focusedRowIndex(rows, this.draft.optionIndex);
465
+ const answer = this.draft.answers[this.draft.currentIndex];
466
+ let focusLine = 0;
467
+
468
+ for (const [rowIndex, row] of rows.entries()) {
469
+ const focused = rowIndex === focusedIndex;
470
+
471
+ if (focused) {
472
+ focusLine = lines.length;
473
+ }
474
+
475
+ for (const line of this.renderRow(question, row, focused, answer, contentWidth)) {
476
+ lines.push(line);
477
+ }
478
+ }
479
+
480
+ return { lines, focusLine };
481
+ }
482
+
483
+ private previewRendererFor(questionIndex: number, question: AskQuestion): QuestionPreviewRenderer {
484
+ const cached = this.previewRenderers.get(questionIndex);
485
+
486
+ if (cached) {
487
+ return cached;
488
+ }
489
+
490
+ const renderer = new QuestionPreviewRenderer({
491
+ question,
492
+ theme: this.theme,
493
+ markdownTheme: getMarkdownTheme(),
494
+ });
495
+
496
+ this.previewRenderers.set(questionIndex, renderer);
497
+
498
+ return renderer;
499
+ }
500
+
501
+ /**
502
+ * Tab strip plus the blank row that separates it from the body below.
503
+ *
504
+ * The strip wraps between tabs, never inside one, so every tab stays one clickable span.
505
+ */
506
+ private renderTabsBlock(contentWidth: number): { lines: string[]; spans: QuestionPanelLayout["tabs"] } {
507
+ const lines: string[] = [];
508
+ const spans: QuestionPanelLayout["tabs"] = [];
509
+ let line = "";
510
+ let column = 0;
511
+
512
+ for (const segment of this.tabSegments()) {
513
+ const text = truncateToWidth(segment.text, contentWidth, "…");
514
+ const width = visibleWidth(text);
515
+
516
+ if (column > 0 && column + width > contentWidth) {
517
+ if (segment.target === undefined) {
518
+ // A separator space must not start the next line.
519
+ continue;
520
+ }
521
+
522
+ lines.push(line);
523
+ line = "";
524
+ column = 0;
525
+ }
526
+
527
+ if (segment.target) {
528
+ spans.push({
529
+ y: BODY_TOP + lines.length,
530
+ start: CONTENT_LEFT + column,
531
+ end: CONTENT_LEFT + column + width,
532
+ target: segment.target,
533
+ });
534
+ }
535
+
536
+ line += segment.style(text);
537
+ column += width;
538
+ }
539
+
540
+ lines.push(line, "");
541
+
542
+ return { lines, spans };
543
+ }
544
+
545
+ private tabSegments(): Array<{ text: string; style: (text: string) => string; target?: TabTarget }> {
546
+ const plain = (text: string) => text;
547
+ const segments: ReturnType<QuestionPanelRenderer["tabSegments"]> = [
548
+ { text: "←", style: plain, target: { kind: "step", step: -1 } },
549
+ { text: " ", style: plain },
550
+ ];
551
+
552
+ for (const [index, question] of this.questions.entries()) {
553
+ const answered = this.draft.answers[index] !== undefined;
554
+ const active = !this.isSubmitTab && index === this.draft.currentIndex;
555
+
556
+ segments.push({
557
+ text: ` ${answered ? "■" : "□"} ${questionTabLabel(question)} `,
558
+ style: (text) => active
559
+ ? this.theme.bg("selectedBg", this.theme.fg("text", text))
560
+ : this.theme.fg(answered ? "success" : "muted", text),
561
+ target: { kind: "tab", index },
562
+ });
563
+ segments.push({ text: " ", style: plain });
564
+ }
565
+
566
+ segments.push(
567
+ {
568
+ text: " ✓ Submit ",
569
+ style: (text) => this.isSubmitTab
570
+ ? this.theme.bg("selectedBg", this.theme.fg("text", text))
571
+ : this.theme.fg(this.allAnswered() ? "success" : "dim", text),
572
+ target: { kind: "tab", index: this.questions.length },
573
+ },
574
+ { text: "→", style: plain, target: { kind: "step", step: 1 } },
575
+ );
576
+
577
+ return segments;
578
+ }
579
+
580
+ private renderRow(
581
+ question: AskQuestion,
582
+ row: QuestionRow,
583
+ focused: boolean,
584
+ answer: AskQuestionAnswer | undefined,
585
+ contentWidth: number,
586
+ ): string[] {
587
+ const lines: string[] = [];
588
+
589
+ if (row.kind === "option") {
590
+ const option = question.options?.[row.index];
591
+
592
+ if (!option) {
593
+ return lines;
594
+ }
595
+
596
+ const chosen = answer?.selectedIndexes.includes(row.index) ?? false;
597
+ const cursor = focused ? this.theme.fg("accent", "›") : " ";
598
+ const marker = question.multiSelect === true
599
+ ? this.theme.fg(chosen ? "success" : "dim", chosen ? "[x]" : "[ ]")
600
+ : this.theme.fg(chosen ? "success" : "dim", chosen ? "●" : "○");
601
+ const label = `${row.index + 1}. ${option.label}`;
602
+ const labelColor: ThemeColor = focused || chosen ? "accent" : "text";
603
+
604
+ pushWrapped(
605
+ lines,
606
+ contentWidth,
607
+ `${cursor} ${marker} `,
608
+ this.theme.fg(labelColor, focused ? this.theme.bold(label) : label),
609
+ );
610
+
611
+ if (option.description) {
612
+ pushWrapped(lines, contentWidth, " ", this.theme.fg("muted", option.description));
613
+ }
614
+
615
+ return lines;
616
+ }
617
+
618
+ if (row.kind === "custom") {
619
+ const questionIndex = this.draft.currentIndex;
620
+ // Only a committed answer is shown here. Mirroring the draft would make the row
621
+ // rewrite itself on every keystroke while the editor below shows the same text,
622
+ // and it would follow edits to an answer that was already written.
623
+ const written = this.draft.answers[questionIndex]?.customText;
624
+
625
+ if (written !== undefined && written.length > 0) {
626
+ pushWrapped(
627
+ lines,
628
+ contentWidth,
629
+ `${focused ? this.theme.fg("accent", "›") : " "} ${this.theme.fg("dim", "✎")} `,
630
+ this.theme.fg(focused ? "accent" : "text", summarizeText(written, Math.max(4, contentWidth - 8))),
631
+ );
632
+ } else {
633
+ pushWrapped(
634
+ lines,
635
+ contentWidth,
636
+ `${focused ? this.theme.fg("accent", "›") : " "} ${this.theme.fg("dim", "✎")} `,
637
+ this.theme.fg(focused ? "accent" : "text", "Type something"),
638
+ );
639
+ pushWrapped(lines, contentWidth, " ", this.theme.fg("muted", "write your own answer"));
640
+ }
641
+
642
+ return lines;
643
+ }
644
+
645
+ pushWrapped(
646
+ lines,
647
+ contentWidth,
648
+ `${focused ? this.theme.fg("accent", "›") : " "} ${this.theme.fg("dim", "→")} `,
649
+ this.theme.fg(focused ? "accent" : "text", "Next"),
650
+ );
651
+ pushWrapped(lines, contentWidth, " ", this.theme.fg("muted", "confirm the selection"));
652
+
653
+ return lines;
654
+ }
655
+
656
+ private renderSubmit(contentWidth: number): string[] {
657
+ const lines: string[] = [];
658
+
659
+ pushWrapped(lines, contentWidth, "", this.theme.fg("accent", this.theme.bold("Ready to submit")));
660
+ lines.push("");
661
+
662
+ for (const [index, question] of this.questions.entries()) {
663
+ const answer = this.draft.answers[index];
664
+
665
+ pushWrapped(
666
+ lines,
667
+ contentWidth,
668
+ "",
669
+ `${this.theme.fg("muted", questionHeaderPrefix(question))}${this.theme.fg("text", summarizeText(question.question, 48))}`,
670
+ );
671
+
672
+ const summary = formatAnswer(question, answer);
673
+
674
+ pushWrapped(
675
+ lines,
676
+ contentWidth,
677
+ " ",
678
+ summary === undefined
679
+ ? this.theme.fg("warning", "unanswered")
680
+ : this.theme.fg("text", summary),
681
+ );
682
+ }
683
+
684
+ lines.push("");
685
+
686
+ if (this.allAnswered()) {
687
+ pushWrapped(lines, contentWidth, "", this.theme.fg("success", "Press Enter to submit"));
688
+ } else {
689
+ const missing = this.questions
690
+ .filter((_, index) => this.draft.answers[index] === undefined)
691
+ .map((question) => questionTabLabel(question))
692
+ .join(", ");
693
+
694
+ pushWrapped(lines, contentWidth, "", this.theme.fg("warning", `Unanswered: ${missing}`));
695
+ }
696
+
697
+ return lines;
698
+ }
699
+
700
+ private markdownFor(text: string): Markdown {
701
+ if (!this.markdown || this.markdownText !== text) {
702
+ this.markdown = new Markdown(text, 0, 0, getMarkdownTheme());
703
+ this.markdownText = text;
704
+ }
705
+
706
+ return this.markdown;
707
+ }
708
+
709
+ private frame(text: string): string {
710
+ return this.theme.fg("border", text);
711
+ }
712
+
713
+ private cell(text: string, width: number): string {
714
+ return ` ${truncateToWidth(text, Math.max(0, width - 2), "…", true)} `;
715
+ }
716
+ }
717
+
718
+ /** Option rows, optionally with the preview block, and where each part landed. */
719
+ interface OptionRegion {
720
+ lines: string[];
721
+ focusLine: number;
722
+ preview?: NonNullable<BodyMarks["preview"]>;
723
+ }
724
+
725
+ /**
726
+ * Window over the body. Without an explicit scroll it keeps the focused row visible without
727
+ * following the tail; a wheel scroll pins it wherever the user left it.
728
+ *
729
+ * `keep` is the answer editor while it owns the keys: the window is nudged the least it can to
730
+ * hold that block, and when even the block does not fit, to hold its cursor line. A wheel
731
+ * scroll is the reader's own position, so it is never pulled back to the editor.
732
+ */
733
+ function bodyWindow(
734
+ length: number,
735
+ focusLine: number,
736
+ height: number,
737
+ scroll: number | undefined,
738
+ keep: RenderedBody["keep"],
739
+ ): { offset: number; maxOffset: number } {
740
+ const maxOffset = Math.max(0, length - height);
741
+ const wanted = scroll ?? focusLine - Math.floor(height / 2);
742
+ let offset = Math.min(maxOffset, Math.max(0, wanted));
743
+
744
+ if (keep && scroll === undefined) {
745
+ if (keep.bottom - keep.top + 1 <= height) {
746
+ if (keep.top < offset) {
747
+ offset = keep.top;
748
+ } else if (keep.bottom >= offset + height) {
749
+ offset = keep.bottom - height + 1;
750
+ }
751
+ } else if (keep.cursor < offset || keep.cursor >= offset + height) {
752
+ offset = keep.cursor - height + 1;
753
+ }
754
+
755
+ offset = Math.min(maxOffset, Math.max(0, offset));
756
+ }
757
+
758
+ return { offset, maxOffset };
759
+ }
760
+
761
+ /**
762
+ * Join the option column and the preview box row by row.
763
+ *
764
+ * The box is right-aligned inside its column so its border lines up with the panel border
765
+ * instead of leaving an invisible tail of blank columns.
766
+ */
767
+ function composeColumns(
768
+ left: { lines: readonly string[]; focusLine: number },
769
+ right: readonly string[],
770
+ columns: { leftWidth: number; rightWidth: number; gap: number },
771
+ contentWidth: number,
772
+ ): { lines: string[]; focusLine: number } {
773
+ const gap = " ".repeat(columns.gap);
774
+ const height = Math.max(left.lines.length, right.length);
775
+ const lines: string[] = [];
776
+
777
+ for (let index = 0; index < height; index++) {
778
+ const leftCell = padEndCell(left.lines[index] ?? "", columns.leftWidth);
779
+ const rightCell = padStartCell(right[index] ?? "", columns.rightWidth);
780
+
781
+ lines.push(truncateToWidth(`${leftCell}${gap}${rightCell}`, contentWidth, "…", true));
782
+ }
783
+
784
+ return { lines, focusLine: left.focusLine };
785
+ }
786
+
787
+ function padEndCell(text: string, width: number): string {
788
+ const clipped = truncateToWidth(text, width, "…");
789
+
790
+ return clipped + " ".repeat(Math.max(0, width - visibleWidth(clipped)));
791
+ }
792
+
793
+ function padStartCell(text: string, width: number): string {
794
+ const clipped = truncateToWidth(text, width, "…");
795
+
796
+ return " ".repeat(Math.max(0, width - visibleWidth(clipped))) + clipped;
797
+ }
798
+
799
+ function pushWrapped(
800
+ lines: string[],
801
+ contentWidth: number,
802
+ prefix: string,
803
+ text: string,
804
+ ): void {
805
+ const prefixWidth = visibleWidth(prefix);
806
+ const available = Math.max(1, contentWidth - prefixWidth);
807
+ const wrapped = wrapTextWithAnsi(text, available);
808
+ const continuation = " ".repeat(prefixWidth);
809
+
810
+ for (const [index, line] of wrapped.entries()) {
811
+ lines.push(truncateToWidth(`${index === 0 ? prefix : continuation}${line}`, contentWidth, "…", true));
812
+ }
813
+ }