@milanglacier/pi-plan-mode 0.5.1

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/qna/qna-tui.ts ADDED
@@ -0,0 +1,877 @@
1
+ import { requirePiTuiModule } from "./pi-tui-loader.js";
2
+
3
+ type Component = {
4
+ handleInput: (data: string) => void;
5
+ render: (width: number) => string[];
6
+ invalidate: () => void;
7
+ };
8
+
9
+ type TUI = {
10
+ requestRender: () => void;
11
+ };
12
+
13
+ type EditorTheme = {
14
+ borderColor: (text: string) => string;
15
+ selectList: {
16
+ matchHighlight?: (text: string) => string;
17
+ itemSecondary?: (text: string) => string;
18
+ };
19
+ };
20
+
21
+ function getPiTui() {
22
+ return requirePiTuiModule() as {
23
+ Editor: new (
24
+ tui: TUI,
25
+ theme: EditorTheme,
26
+ ) => {
27
+ disableSubmit?: boolean;
28
+ onChange?: () => void;
29
+ setText: (text: string) => void;
30
+ getText: () => string;
31
+ render: (width: number) => string[];
32
+ handleInput: (data: string) => void;
33
+ };
34
+ Key: {
35
+ enter: string;
36
+ tab: string;
37
+ escape: string;
38
+ up: string;
39
+ down: string;
40
+ ctrl: (key: string) => string;
41
+ shift: (key: string) => string;
42
+ };
43
+ matchesKey: (input: string, key: string) => boolean;
44
+ truncateToWidth: (text: string, width: number) => string;
45
+ visibleWidth: (text: string) => number;
46
+ wrapTextWithAnsi: (text: string, width: number) => string[];
47
+ };
48
+ }
49
+
50
+ export interface QnAOption {
51
+ label: string;
52
+ description: string;
53
+ recommended?: boolean;
54
+ }
55
+
56
+ export interface QnAQuestion {
57
+ header?: string;
58
+ question: string;
59
+ context?: string;
60
+ fullContext?: string;
61
+ options?: QnAOption[];
62
+ }
63
+
64
+ export interface QnATemplate {
65
+ label: string;
66
+ template: string;
67
+ }
68
+
69
+ export interface QnAResponse {
70
+ selectedOptionIndex: number;
71
+ customText: string;
72
+ selectionTouched: boolean;
73
+ committed: boolean;
74
+ }
75
+
76
+ export interface QnAResult {
77
+ text: string;
78
+ answers: string[];
79
+ responses: QnAResponse[];
80
+ }
81
+
82
+ export interface QnATemplateData {
83
+ question: string;
84
+ context?: string;
85
+ answer: string;
86
+ index: number;
87
+ total: number;
88
+ }
89
+
90
+ export function getQuestionOptions(question: QnAQuestion): QnAOption[] {
91
+ return question.options ?? [];
92
+ }
93
+
94
+ export function formatResponseAnswer(question: QnAQuestion, response: QnAResponse): string {
95
+ const options = getQuestionOptions(question);
96
+ if (options.length === 0) {
97
+ return response.customText;
98
+ }
99
+
100
+ const otherIndex = options.length;
101
+ if (response.selectedOptionIndex === otherIndex) {
102
+ return response.customText;
103
+ }
104
+
105
+ if (!response.selectionTouched) {
106
+ return "";
107
+ }
108
+
109
+ return options[response.selectedOptionIndex]?.label ?? "";
110
+ }
111
+
112
+ export function normalizeResponseForQuestion(
113
+ question: QnAQuestion,
114
+ response: Partial<QnAResponse> | undefined,
115
+ fallbackAnswer: string | undefined,
116
+ inferCommittedFromContent: boolean,
117
+ ): QnAResponse {
118
+ const options = getQuestionOptions(question);
119
+ const rawFallback = fallbackAnswer ?? "";
120
+ const rawCustomText = response?.customText ?? rawFallback;
121
+ let selectedOptionIndex =
122
+ typeof response?.selectedOptionIndex === "number" && Number.isFinite(response.selectedOptionIndex)
123
+ ? Math.trunc(response.selectedOptionIndex)
124
+ : undefined;
125
+ let selectionTouched = response?.selectionTouched ?? false;
126
+
127
+ if (options.length === 0) {
128
+ selectedOptionIndex = 0;
129
+ if (response?.selectionTouched === undefined && rawCustomText.trim().length > 0) {
130
+ selectionTouched = true;
131
+ }
132
+ } else if (selectedOptionIndex === undefined) {
133
+ const fallbackTrimmed = rawFallback.trim();
134
+ if (fallbackTrimmed.length === 0) {
135
+ selectedOptionIndex = 0;
136
+ if (response?.selectionTouched === undefined) {
137
+ selectionTouched = false;
138
+ }
139
+ } else {
140
+ const optionIndex = options.findIndex((option) => option.label === fallbackTrimmed);
141
+ selectedOptionIndex = optionIndex >= 0 ? optionIndex : options.length;
142
+ if (response?.selectionTouched === undefined) {
143
+ selectionTouched = true;
144
+ }
145
+ }
146
+ } else if (response?.selectionTouched === undefined) {
147
+ selectionTouched = response?.committed === true;
148
+ if (!selectionTouched) {
149
+ const fallbackTrimmed = rawFallback.trim();
150
+ if (fallbackTrimmed.length > 0) {
151
+ const optionIndex = options.findIndex((option) => option.label === fallbackTrimmed);
152
+ if (optionIndex >= 0) {
153
+ selectionTouched = optionIndex === selectedOptionIndex && optionIndex !== 0;
154
+ } else {
155
+ selectionTouched = selectedOptionIndex === options.length;
156
+ }
157
+ }
158
+ }
159
+ }
160
+
161
+ const maxIndex = options.length;
162
+ const normalizedIndex = Math.max(0, Math.min(maxIndex, selectedOptionIndex ?? 0));
163
+ const useCustomText = options.length === 0 || normalizedIndex === options.length;
164
+ const normalizedCustomText = useCustomText ? rawCustomText : "";
165
+
166
+ let committed = response?.committed ?? false;
167
+ if (response?.committed === undefined && inferCommittedFromContent) {
168
+ committed =
169
+ formatResponseAnswer(question, {
170
+ selectedOptionIndex: normalizedIndex,
171
+ customText: normalizedCustomText,
172
+ selectionTouched,
173
+ committed: false,
174
+ }).trim().length > 0;
175
+ }
176
+
177
+ return {
178
+ selectedOptionIndex: normalizedIndex,
179
+ customText: normalizedCustomText,
180
+ selectionTouched,
181
+ committed,
182
+ };
183
+ }
184
+
185
+ export function normalizeResponses(
186
+ questions: QnAQuestion[],
187
+ responses: Array<Partial<QnAResponse>> | undefined,
188
+ fallbackAnswers: string[] | undefined,
189
+ inferCommittedFromContent: boolean,
190
+ ): QnAResponse[] {
191
+ return questions.map((question, index) =>
192
+ normalizeResponseForQuestion(question, responses?.[index], fallbackAnswers?.[index], inferCommittedFromContent),
193
+ );
194
+ }
195
+
196
+ export function cloneResponses(responses: QnAResponse[]): QnAResponse[] {
197
+ return responses.map((response) => ({ ...response }));
198
+ }
199
+
200
+ export function deriveAnswersFromResponses(questions: QnAQuestion[], responses: QnAResponse[]): string[] {
201
+ return questions.map((question, index) => formatResponseAnswer(question, responses[index]));
202
+ }
203
+
204
+ export function hasResponseContent(question: QnAQuestion, response: QnAResponse): boolean {
205
+ return formatResponseAnswer(question, response).trim().length > 0;
206
+ }
207
+
208
+ function defaultResolveNumericShortcut(
209
+ input: string,
210
+ maxOptionIndex: number,
211
+ usingCustomEditor: boolean,
212
+ ): number | null {
213
+ if (usingCustomEditor) {
214
+ return null;
215
+ }
216
+
217
+ if (!/^[1-9]$/.test(input)) {
218
+ return null;
219
+ }
220
+
221
+ const selectedIndex = Number(input) - 1;
222
+ if (selectedIndex > maxOptionIndex) {
223
+ return null;
224
+ }
225
+
226
+ return selectedIndex;
227
+ }
228
+
229
+ function defaultApplyTemplate(template: string, data: QnATemplateData): string {
230
+ const replacements: Record<string, string> = {
231
+ question: data.question,
232
+ context: data.context ?? "",
233
+ answer: data.answer,
234
+ index: String(data.index + 1),
235
+ total: String(data.total),
236
+ };
237
+
238
+ return template.replace(/\{\{(question|context|answer|index|total)\}\}/g, (_match, key: string) => {
239
+ return replacements[key] ?? "";
240
+ });
241
+ }
242
+
243
+ function summarizeAnswer(text: string, maxLength: number = 60): string {
244
+ const singleLine = text.replace(/\s+/g, " ").trim();
245
+ if (singleLine.length <= maxLength) {
246
+ return singleLine;
247
+ }
248
+ return `${singleLine.slice(0, maxLength - 1)}…`;
249
+ }
250
+
251
+ export class QnATuiComponent<TQuestion extends QnAQuestion> implements Component {
252
+ private questions: TQuestion[];
253
+ private responses: QnAResponse[];
254
+ private currentIndex = 0;
255
+ private editor: {
256
+ disableSubmit?: boolean;
257
+ onChange?: () => void;
258
+ setText: (text: string) => void;
259
+ getText: () => string;
260
+ render: (width: number) => string[];
261
+ handleInput: (data: string) => void;
262
+ };
263
+ private tui: TUI;
264
+ private onDone: (result: QnAResult | null) => void;
265
+ private showingConfirmation = false;
266
+ private showingContextPopup = false;
267
+ private templates: QnATemplate[];
268
+ private templateIndex = 0;
269
+ private onResponsesChange?: (responses: QnAResponse[]) => void;
270
+ private title: string;
271
+ private resolveNumericShortcut: (input: string, maxOptionIndex: number, usingCustomEditor: boolean) => number | null;
272
+ private applyTemplate: (template: string, data: QnATemplateData) => string;
273
+ private questionSummaryLabel: (question: TQuestion, index: number) => string;
274
+
275
+ private cachedWidth?: number;
276
+ private cachedLines?: string[];
277
+
278
+ private dim = (s: string) => s;
279
+ private bold = (s: string) => s;
280
+ private italic = (s: string) => `\x1b[3m${s}\x1b[0m`;
281
+ private cyan = (s: string) => s;
282
+ private green = (s: string) => s;
283
+ private yellow = (s: string) => s;
284
+ private gray = (s: string) => s;
285
+
286
+ constructor(
287
+ questions: TQuestion[],
288
+ tui: TUI,
289
+ onDone: (result: QnAResult | null) => void,
290
+ options?: {
291
+ title?: string;
292
+ templates?: QnATemplate[];
293
+ initialResponses?: Array<Partial<QnAResponse>>;
294
+ fallbackAnswers?: string[];
295
+ inferCommittedFromContent?: boolean;
296
+ onResponsesChange?: (responses: QnAResponse[]) => void;
297
+ resolveNumericShortcut?: (input: string, maxOptionIndex: number, usingCustomEditor: boolean) => number | null;
298
+ applyTemplate?: (template: string, data: QnATemplateData) => string;
299
+ questionSummaryLabel?: (question: TQuestion, index: number) => string;
300
+ accentColor?: (text: string) => string;
301
+ successColor?: (text: string) => string;
302
+ warningColor?: (text: string) => string;
303
+ mutedColor?: (text: string) => string;
304
+ dimColor?: (text: string) => string;
305
+ boldText?: (text: string) => string;
306
+ italicText?: (text: string) => string;
307
+ },
308
+ ) {
309
+ this.questions = questions;
310
+ this.templates = options?.templates ?? [];
311
+ this.responses = normalizeResponses(
312
+ questions,
313
+ options?.initialResponses,
314
+ options?.fallbackAnswers,
315
+ options?.inferCommittedFromContent ?? false,
316
+ );
317
+ this.tui = tui;
318
+ this.onDone = onDone;
319
+ this.onResponsesChange = options?.onResponsesChange;
320
+ this.title = options?.title ?? "Questions";
321
+ this.resolveNumericShortcut = options?.resolveNumericShortcut ?? defaultResolveNumericShortcut;
322
+ this.applyTemplate = options?.applyTemplate ?? defaultApplyTemplate;
323
+ this.questionSummaryLabel =
324
+ options?.questionSummaryLabel ??
325
+ ((question) => {
326
+ return question.header?.trim() || question.question;
327
+ });
328
+ this.cyan = options?.accentColor ?? this.cyan;
329
+ this.green = options?.successColor ?? this.green;
330
+ this.yellow = options?.warningColor ?? this.yellow;
331
+ this.gray = options?.mutedColor ?? this.gray;
332
+ this.dim = options?.dimColor ?? this.dim;
333
+ this.bold = options?.boldText ?? this.bold;
334
+ this.italic = options?.italicText ?? this.italic;
335
+
336
+ const editorTheme: EditorTheme = {
337
+ borderColor: this.dim,
338
+ selectList: {
339
+ matchHighlight: this.cyan,
340
+ itemSecondary: this.gray,
341
+ },
342
+ };
343
+
344
+ const { Editor } = getPiTui();
345
+ this.editor = new Editor(tui, editorTheme);
346
+ this.editor.disableSubmit = true;
347
+ this.editor.onChange = () => {
348
+ this.saveCurrentResponse();
349
+ this.invalidate();
350
+ this.tui.requestRender();
351
+ };
352
+
353
+ this.loadEditorForCurrentQuestion();
354
+ }
355
+
356
+ private getCurrentQuestion(): TQuestion {
357
+ return this.questions[this.currentIndex];
358
+ }
359
+
360
+ private isPrintableInput(data: string): boolean {
361
+ if (data.length !== 1) {
362
+ return false;
363
+ }
364
+
365
+ const code = data.charCodeAt(0);
366
+ return code >= 32 && code !== 127;
367
+ }
368
+
369
+ private shouldUseEditor(index: number = this.currentIndex): boolean {
370
+ const question = this.questions[index];
371
+ const options = getQuestionOptions(question);
372
+ if (options.length === 0) {
373
+ return true;
374
+ }
375
+
376
+ return this.responses[index].selectedOptionIndex === options.length;
377
+ }
378
+
379
+ private getCurrentAnswerText(): string {
380
+ const question = this.getCurrentQuestion();
381
+ const response = this.responses[this.currentIndex];
382
+ return formatResponseAnswer(question, response);
383
+ }
384
+
385
+ private getAnswerText(index: number): string {
386
+ return formatResponseAnswer(this.questions[index], this.responses[index]);
387
+ }
388
+
389
+ private emitResponseChange(): void {
390
+ this.onResponsesChange?.(cloneResponses(this.responses));
391
+ }
392
+
393
+ private loadEditorForCurrentQuestion(): void {
394
+ if (!this.shouldUseEditor()) {
395
+ this.editor.setText("");
396
+ return;
397
+ }
398
+
399
+ this.editor.setText(this.responses[this.currentIndex].customText ?? "");
400
+ }
401
+
402
+ private saveCurrentResponse(emit: boolean = true): void {
403
+ if (this.shouldUseEditor()) {
404
+ const text = this.editor.getText();
405
+ this.responses[this.currentIndex].customText = text;
406
+ const question = this.questions[this.currentIndex];
407
+ if (getQuestionOptions(question).length === 0 || text.trim().length > 0) {
408
+ this.responses[this.currentIndex].selectionTouched = true;
409
+ }
410
+ }
411
+
412
+ if (emit) {
413
+ this.emitResponseChange();
414
+ }
415
+ }
416
+
417
+ private navigateTo(index: number): void {
418
+ if (index < 0 || index >= this.questions.length) {
419
+ return;
420
+ }
421
+
422
+ this.saveCurrentResponse();
423
+ this.currentIndex = index;
424
+ this.showingConfirmation = false;
425
+ this.loadEditorForCurrentQuestion();
426
+ this.invalidate();
427
+ }
428
+
429
+ private selectOption(index: number): void {
430
+ const question = this.getCurrentQuestion();
431
+ const options = getQuestionOptions(question);
432
+ if (options.length === 0) {
433
+ return;
434
+ }
435
+
436
+ const maxIndex = options.length;
437
+ const normalized = Math.max(0, Math.min(maxIndex, index));
438
+ const currentResponse = this.responses[this.currentIndex];
439
+ if (normalized === currentResponse.selectedOptionIndex && currentResponse.selectionTouched) {
440
+ return;
441
+ }
442
+
443
+ this.saveCurrentResponse(false);
444
+ currentResponse.selectedOptionIndex = normalized;
445
+ currentResponse.selectionTouched = true;
446
+ this.loadEditorForCurrentQuestion();
447
+ this.emitResponseChange();
448
+ this.invalidate();
449
+ this.tui.requestRender();
450
+ }
451
+
452
+ private applyNextTemplate(): void {
453
+ if (this.templates.length === 0) {
454
+ return;
455
+ }
456
+
457
+ const question = this.getCurrentQuestion();
458
+ const options = getQuestionOptions(question);
459
+ if (options.length > 0 && !this.shouldUseEditor()) {
460
+ this.selectOption(options.length);
461
+ }
462
+
463
+ const template = this.templates[this.templateIndex];
464
+ const updated = this.applyTemplate(template.template, {
465
+ question: question.question,
466
+ context: question.context,
467
+ answer: this.getCurrentAnswerText(),
468
+ index: this.currentIndex,
469
+ total: this.questions.length,
470
+ });
471
+
472
+ this.editor.setText(updated);
473
+ this.saveCurrentResponse();
474
+ this.templateIndex = (this.templateIndex + 1) % this.templates.length;
475
+ this.invalidate();
476
+ this.tui.requestRender();
477
+ }
478
+
479
+ private submit(): void {
480
+ this.saveCurrentResponse();
481
+
482
+ const answers = deriveAnswersFromResponses(this.questions, this.responses);
483
+ const parts: string[] = [];
484
+ for (let i = 0; i < this.questions.length; i++) {
485
+ const question = this.questions[i];
486
+ const rawAnswer = answers[i] ?? "";
487
+ if (rawAnswer.trim().length === 0) {
488
+ continue;
489
+ }
490
+
491
+ parts.push(`Q: ${question.question}`);
492
+ parts.push(`A: ${rawAnswer}`);
493
+ parts.push("");
494
+ }
495
+
496
+ this.onDone({
497
+ text: parts.join("\n").trim(),
498
+ answers,
499
+ responses: cloneResponses(this.responses),
500
+ });
501
+ }
502
+
503
+ private cancel(): void {
504
+ this.onDone(null);
505
+ }
506
+
507
+ invalidate(): void {
508
+ this.cachedWidth = undefined;
509
+ this.cachedLines = undefined;
510
+ }
511
+
512
+ handleInput(data: string): void {
513
+ const { Key, matchesKey } = getPiTui();
514
+
515
+ if (this.showingConfirmation) {
516
+ if (matchesKey(data, Key.enter)) {
517
+ this.submit();
518
+ return;
519
+ }
520
+ if (matchesKey(data, Key.ctrl("c"))) {
521
+ this.cancel();
522
+ return;
523
+ }
524
+ if (matchesKey(data, Key.escape)) {
525
+ this.showingConfirmation = false;
526
+ this.invalidate();
527
+ this.tui.requestRender();
528
+ return;
529
+ }
530
+ return;
531
+ }
532
+
533
+ if (matchesKey(data, Key.ctrl("c"))) {
534
+ this.cancel();
535
+ return;
536
+ }
537
+
538
+ if (matchesKey(data, Key.ctrl("o"))) {
539
+ if (this.showingContextPopup) {
540
+ this.showingContextPopup = false;
541
+ this.invalidate();
542
+ this.tui.requestRender();
543
+ } else if (this.getCurrentQuestion().fullContext) {
544
+ this.showingContextPopup = true;
545
+ this.invalidate();
546
+ this.tui.requestRender();
547
+ }
548
+ return;
549
+ }
550
+
551
+ if (this.showingContextPopup) {
552
+ if (matchesKey(data, Key.escape) || matchesKey(data, Key.enter) || matchesKey(data, Key.ctrl("o"))) {
553
+ this.showingContextPopup = false;
554
+ this.invalidate();
555
+ this.tui.requestRender();
556
+ }
557
+ return;
558
+ }
559
+
560
+ if (matchesKey(data, Key.ctrl("t"))) {
561
+ this.applyNextTemplate();
562
+ return;
563
+ }
564
+
565
+ if (matchesKey(data, Key.tab)) {
566
+ if (this.currentIndex < this.questions.length - 1) {
567
+ this.navigateTo(this.currentIndex + 1);
568
+ this.tui.requestRender();
569
+ }
570
+ return;
571
+ }
572
+
573
+ if (matchesKey(data, Key.shift("tab"))) {
574
+ if (this.currentIndex > 0) {
575
+ this.navigateTo(this.currentIndex - 1);
576
+ this.tui.requestRender();
577
+ }
578
+ return;
579
+ }
580
+
581
+ const question = this.getCurrentQuestion();
582
+ const options = getQuestionOptions(question);
583
+ const usingEditor = this.shouldUseEditor();
584
+ if (options.length > 0) {
585
+ const otherIndex = options.length;
586
+ const isOnOther = this.responses[this.currentIndex].selectedOptionIndex === otherIndex;
587
+ const canSwitchFromCustomInput = usingEditor && isOnOther && this.editor.getText().length === 0;
588
+ const allowOptionNavigation = !usingEditor || canSwitchFromCustomInput;
589
+
590
+ if (allowOptionNavigation && matchesKey(data, Key.up)) {
591
+ this.selectOption(this.responses[this.currentIndex].selectedOptionIndex - 1);
592
+ return;
593
+ }
594
+
595
+ if (allowOptionNavigation && matchesKey(data, Key.down)) {
596
+ this.selectOption(this.responses[this.currentIndex].selectedOptionIndex + 1);
597
+ return;
598
+ }
599
+
600
+ const selectedIndex = this.resolveNumericShortcut(data, otherIndex, usingEditor);
601
+ if (selectedIndex !== null) {
602
+ this.selectOption(selectedIndex);
603
+ return;
604
+ }
605
+ }
606
+
607
+ if (matchesKey(data, Key.enter) && !matchesKey(data, Key.shift("enter"))) {
608
+ const currentResponse = this.responses[this.currentIndex];
609
+ if (options.length > 0 && !this.shouldUseEditor() && !currentResponse.selectionTouched) {
610
+ currentResponse.selectionTouched = true;
611
+ }
612
+
613
+ this.saveCurrentResponse();
614
+ currentResponse.committed = true;
615
+ this.emitResponseChange();
616
+ if (this.currentIndex < this.questions.length - 1) {
617
+ this.navigateTo(this.currentIndex + 1);
618
+ } else {
619
+ this.showingConfirmation = true;
620
+ }
621
+ this.invalidate();
622
+ this.tui.requestRender();
623
+ return;
624
+ }
625
+
626
+ if (this.shouldUseEditor()) {
627
+ this.editor.handleInput(data);
628
+ this.invalidate();
629
+ this.tui.requestRender();
630
+ return;
631
+ }
632
+
633
+ if (this.isPrintableInput(data)) {
634
+ this.selectOption(getQuestionOptions(question).length);
635
+ this.editor.handleInput(data);
636
+ this.saveCurrentResponse();
637
+ this.invalidate();
638
+ this.tui.requestRender();
639
+ }
640
+ }
641
+
642
+ render(width: number): string[] {
643
+ const { truncateToWidth, visibleWidth, wrapTextWithAnsi } = getPiTui();
644
+
645
+ if (this.cachedLines && this.cachedWidth === width) {
646
+ return this.cachedLines;
647
+ }
648
+
649
+ const lines: string[] = [];
650
+ const boxWidth = Math.max(40, Math.min(width - 4, 120));
651
+ const contentWidth = boxWidth - 4;
652
+
653
+ const horizontalLine = (count: number) => "─".repeat(count);
654
+
655
+ const boxLine = (content: string, leftPad: number = 2): string => {
656
+ const safeLeftPad = Math.max(0, Math.min(leftPad, boxWidth - 2));
657
+ const clippedContent = truncateToWidth(content, Math.max(0, boxWidth - safeLeftPad - 2));
658
+ const paddedContent = " ".repeat(safeLeftPad) + clippedContent;
659
+ const contentLen = visibleWidth(paddedContent);
660
+ const rightPad = Math.max(0, boxWidth - contentLen - 2);
661
+ return this.dim("│") + paddedContent + " ".repeat(rightPad) + this.dim("│");
662
+ };
663
+
664
+ const emptyBoxLine = (): string => {
665
+ return this.dim("│") + " ".repeat(boxWidth - 2) + this.dim("│");
666
+ };
667
+
668
+ const padToWidth = (line: string): string => {
669
+ const len = visibleWidth(line);
670
+ return line + " ".repeat(Math.max(0, width - len));
671
+ };
672
+
673
+ const question = this.getCurrentQuestion();
674
+ const response = this.responses[this.currentIndex];
675
+ const options = getQuestionOptions(question);
676
+ const usesEditor = this.shouldUseEditor();
677
+
678
+ lines.push(padToWidth(this.dim(`╭${horizontalLine(boxWidth - 2)}╮`)));
679
+ const title = `${this.title} ${this.dim(`(${this.currentIndex + 1}/${this.questions.length})`)}`;
680
+ lines.push(padToWidth(boxLine(title)));
681
+ lines.push(padToWidth(this.dim(`├${horizontalLine(boxWidth - 2)}┤`)));
682
+
683
+ const progressParts: string[] = [];
684
+ for (let i = 0; i < this.questions.length; i++) {
685
+ const current = i === this.currentIndex;
686
+ const answered = hasResponseContent(this.questions[i], this.responses[i]);
687
+ if (current) {
688
+ progressParts.push(this.cyan("●"));
689
+ } else if (answered) {
690
+ progressParts.push(this.green("●"));
691
+ } else {
692
+ progressParts.push(this.dim("○"));
693
+ }
694
+ }
695
+ lines.push(padToWidth(boxLine(progressParts.join(" "))));
696
+
697
+ if (!this.showingConfirmation) {
698
+ if (this.showingContextPopup && question.fullContext) {
699
+ lines.push(padToWidth(emptyBoxLine()));
700
+ lines.push(padToWidth(boxLine(this.bold(this.cyan("Question Details")))));
701
+ lines.push(padToWidth(emptyBoxLine()));
702
+
703
+ const wrappedFull = wrapTextWithAnsi(this.bold("Full question:"), contentWidth);
704
+ for (const line of wrappedFull) {
705
+ lines.push(padToWidth(boxLine(line)));
706
+ }
707
+ for (const line of wrapTextWithAnsi(question.fullContext, contentWidth)) {
708
+ lines.push(padToWidth(boxLine(line)));
709
+ }
710
+
711
+ if (question.context) {
712
+ lines.push(padToWidth(emptyBoxLine()));
713
+ for (const line of wrapTextWithAnsi(this.bold("Context:"), contentWidth)) {
714
+ lines.push(padToWidth(boxLine(line)));
715
+ }
716
+ for (const line of wrapTextWithAnsi(question.context, contentWidth)) {
717
+ lines.push(padToWidth(boxLine(line)));
718
+ }
719
+ }
720
+
721
+ if (options.length > 0) {
722
+ lines.push(padToWidth(emptyBoxLine()));
723
+ for (const line of wrapTextWithAnsi(this.bold("Options:"), contentWidth)) {
724
+ lines.push(padToWidth(boxLine(line)));
725
+ }
726
+ for (let i = 0; i < options.length; i++) {
727
+ const opt = options[i];
728
+ const optLabel = `${i + 1}. ${opt.label}`;
729
+ for (const line of wrapTextWithAnsi(optLabel, contentWidth)) {
730
+ lines.push(padToWidth(boxLine(line)));
731
+ }
732
+ if (opt.description) {
733
+ for (const line of wrapTextWithAnsi(this.gray(` ${opt.description}`), contentWidth)) {
734
+ lines.push(padToWidth(boxLine(line)));
735
+ }
736
+ }
737
+ }
738
+ }
739
+
740
+ lines.push(padToWidth(emptyBoxLine()));
741
+ lines.push(padToWidth(boxLine(this.dim("Esc or Enter to close · Ctrl+O to toggle"))));
742
+ } else {
743
+ if (question.header) {
744
+ lines.push(padToWidth(boxLine(this.cyan(question.header))));
745
+ }
746
+ lines.push(padToWidth(emptyBoxLine()));
747
+
748
+ const wrappedQuestion = wrapTextWithAnsi(`${this.bold("Q:")} ${this.bold(question.question)}`, contentWidth);
749
+ for (const line of wrappedQuestion) {
750
+ lines.push(padToWidth(boxLine(line)));
751
+ }
752
+
753
+ if (question.context) {
754
+ lines.push(padToWidth(emptyBoxLine()));
755
+ for (const line of wrapTextWithAnsi(this.gray(`> ${question.context}`), contentWidth - 2)) {
756
+ lines.push(padToWidth(boxLine(line)));
757
+ }
758
+ }
759
+
760
+ if (options.length > 0) {
761
+ lines.push(padToWidth(emptyBoxLine()));
762
+ for (let i = 0; i <= options.length; i++) {
763
+ const isOther = i === options.length;
764
+ const rawLabel = isOther ? "Other" : options[i].label;
765
+ const isRecommended = !isOther && options[i].recommended;
766
+ const optionLabel = isRecommended ? `${rawLabel} (recommended)` : rawLabel;
767
+ const description = isOther ? "Type your own answer" : options[i].description;
768
+ const selected = response.selectedOptionIndex === i;
769
+ const marker = selected ? "▶" : " ";
770
+ const optionPrefix = `${marker} ${i + 1}. `;
771
+ const line = `${optionPrefix}${optionLabel}`;
772
+ let styledLine: string;
773
+ if (selected) {
774
+ styledLine = response.selectionTouched ? this.green(line) : this.cyan(line);
775
+ } else if (isRecommended) {
776
+ styledLine = this.bold(line);
777
+ } else {
778
+ styledLine = line;
779
+ }
780
+ lines.push(padToWidth(boxLine(truncateToWidth(styledLine, contentWidth))));
781
+
782
+ if (selected && description && description.trim().length > 0) {
783
+ const descriptionIndent = " ".repeat(visibleWidth(optionPrefix));
784
+ const wrappedDescription = wrapTextWithAnsi(
785
+ description,
786
+ Math.max(10, contentWidth - visibleWidth(descriptionIndent)),
787
+ );
788
+ for (const wrapped of wrappedDescription) {
789
+ lines.push(padToWidth(boxLine(`${descriptionIndent}${this.gray(wrapped)}`)));
790
+ }
791
+ }
792
+ }
793
+ }
794
+
795
+ lines.push(padToWidth(emptyBoxLine()));
796
+ if (usesEditor) {
797
+ const answerPrefix = this.bold("A: ");
798
+ const editorWidth = Math.max(20, contentWidth - 7);
799
+ const editorLines = this.editor.render(editorWidth);
800
+ for (let i = 1; i < editorLines.length - 1; i++) {
801
+ if (i === 1) {
802
+ lines.push(padToWidth(boxLine(answerPrefix + editorLines[i])));
803
+ } else {
804
+ lines.push(padToWidth(boxLine(" " + editorLines[i])));
805
+ }
806
+ }
807
+ } else {
808
+ const selectedLabel = response.selectionTouched
809
+ ? (options[response.selectedOptionIndex]?.label ?? "")
810
+ : this.dim("(select an option)");
811
+ lines.push(padToWidth(boxLine(`${this.bold("A:")} ${selectedLabel}`)));
812
+ }
813
+ lines.push(padToWidth(emptyBoxLine()));
814
+ }
815
+ }
816
+
817
+ if (this.showingConfirmation) {
818
+ lines.push(padToWidth(this.dim(`├${horizontalLine(boxWidth - 2)}┤`)));
819
+ lines.push(padToWidth(boxLine(this.bold("Review before submit:"))));
820
+ for (let i = 0; i < this.questions.length; i++) {
821
+ const summaryLabel = this.questionSummaryLabel(this.questions[i], i);
822
+ const answerText = this.getAnswerText(i);
823
+ const hasAnswer = answerText.trim().length > 0;
824
+ const answerPreview = hasAnswer ? this.green(summarizeAnswer(answerText)) : this.yellow("(no answer)");
825
+ const questionLine = `${this.bold(`${i + 1}.`)} ${this.cyan(summaryLabel)}`;
826
+ const answerLine = ` ${this.dim("Answer:")} ${answerPreview}`;
827
+ lines.push(padToWidth(boxLine(truncateToWidth(questionLine, contentWidth))));
828
+ lines.push(padToWidth(boxLine(truncateToWidth(answerLine, contentWidth))));
829
+ }
830
+ lines.push(padToWidth(emptyBoxLine()));
831
+ const confirmMsg = `${this.yellow("Submit all answers?")} ${this.dim("(Enter submit, Esc keep editing)")}`;
832
+ lines.push(padToWidth(boxLine(truncateToWidth(confirmMsg, contentWidth))));
833
+ const separator = this.cyan(" · ");
834
+ const formatHint = (shortcut: string, action: string) => `${this.bold(shortcut)} ${this.italic(action)}`;
835
+ const confirmControls = `${formatHint("Enter", "submit")}${separator}${formatHint("Esc", "back")}${separator}${formatHint("Ctrl+C", "cancel")}`;
836
+ lines.push(padToWidth(boxLine(truncateToWidth(confirmControls, contentWidth))));
837
+ } else {
838
+ lines.push(padToWidth(this.dim(`├${horizontalLine(boxWidth - 2)}┤`)));
839
+
840
+ const separator = this.cyan(" · ");
841
+ const formatHint = (shortcut: string, action: string) => `${this.bold(shortcut)} ${this.italic(action)}`;
842
+ const joinHints = (parts: string[]) => parts.join(separator);
843
+ const canFit = (parts: string[]) => visibleWidth(joinHints(parts)) <= contentWidth;
844
+
845
+ const tabHint = formatHint("Tab/⇧Tab", "next/prev");
846
+ const enterHint = formatHint("Enter", "commit + next");
847
+ const cancelHint = formatHint("Ctrl+C", "cancel");
848
+
849
+ const optionalHints: string[] = [];
850
+ if (options.length > 0 && !usesEditor) {
851
+ optionalHints.push(formatHint("↑/↓/1-9", "pick option"));
852
+ }
853
+ if (usesEditor) {
854
+ optionalHints.push(formatHint("⇧Enter", "newline"));
855
+ }
856
+ if (this.templates.length > 0) {
857
+ optionalHints.push(formatHint("Ctrl+T", "template"));
858
+ }
859
+
860
+ const trailingHints = [enterHint, tabHint, cancelHint];
861
+ const controls: string[] = [];
862
+ for (const hint of optionalHints) {
863
+ if (canFit([...controls, hint, ...trailingHints])) {
864
+ controls.push(hint);
865
+ }
866
+ }
867
+ controls.push(...trailingHints);
868
+
869
+ lines.push(padToWidth(boxLine(truncateToWidth(joinHints(controls), contentWidth))));
870
+ }
871
+ lines.push(padToWidth(this.dim(`╰${horizontalLine(boxWidth - 2)}╯`)));
872
+
873
+ this.cachedWidth = width;
874
+ this.cachedLines = lines;
875
+ return lines;
876
+ }
877
+ }