@ifi/pi-shared-qna 0.2.14

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Ifiok Jr.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,7 @@
1
+ # @ifi/pi-shared-qna
2
+
3
+ Shared question-and-answer TUI helpers for pi extensions.
4
+
5
+ This package vendors the `shared/qna-tui.ts` component from
6
+ [`sids/pi-extensions`](https://github.com/sids/pi-extensions) into the oh-pi monorepo so other
7
+ first-party packages can reuse it without depending on third-party pi packages at runtime.
package/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./qna-tui.js";
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@ifi/pi-shared-qna",
3
+ "version": "0.2.14",
4
+ "description": "Shared TUI question-and-answer component for pi extensions.",
5
+ "type": "module",
6
+ "keywords": [
7
+ "pi-package",
8
+ "pi",
9
+ "pi-coding-agent",
10
+ "tui",
11
+ "qna"
12
+ ],
13
+ "exports": {
14
+ ".": "./index.ts",
15
+ "./package.json": "./package.json"
16
+ },
17
+ "files": [
18
+ "*.ts",
19
+ "README.md",
20
+ "!**/*.test.ts",
21
+ "!tests/**"
22
+ ],
23
+ "license": "MIT",
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/ifiokjr/oh-pi.git",
27
+ "directory": "packages/shared-qna"
28
+ },
29
+ "homepage": "https://github.com/ifiokjr/oh-pi/tree/main/packages/shared-qna",
30
+ "bugs": {
31
+ "url": "https://github.com/ifiokjr/oh-pi/issues"
32
+ },
33
+ "peerDependencies": {
34
+ "@mariozechner/pi-tui": "*"
35
+ }
36
+ }
package/qna-tui.ts ADDED
@@ -0,0 +1,826 @@
1
+ import { createRequire } from "node:module";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ const require = createRequire(import.meta.url);
6
+
7
+ function requirePiTui() {
8
+ try {
9
+ return require("@mariozechner/pi-tui");
10
+ } catch (error) {
11
+ const code = (error as { code?: string }).code;
12
+ if (code !== "MODULE_NOT_FOUND") {
13
+ throw error;
14
+ }
15
+ return require(path.join(os.homedir(), ".bun", "install", "global", "node_modules", "@mariozechner", "pi-tui"));
16
+ }
17
+ }
18
+
19
+ type Component = {
20
+ handleInput: (data: string) => void;
21
+ render: (width: number) => string[];
22
+ invalidate: () => void;
23
+ };
24
+
25
+ type TUI = {
26
+ requestRender: () => void;
27
+ };
28
+
29
+ type EditorTheme = {
30
+ borderColor: (text: string) => string;
31
+ selectList: {
32
+ matchHighlight?: (text: string) => string;
33
+ itemSecondary?: (text: string) => string;
34
+ };
35
+ };
36
+
37
+ function getPiTui() {
38
+ return requirePiTui() as {
39
+ Editor: new (tui: TUI, theme: EditorTheme) => {
40
+ disableSubmit?: boolean;
41
+ onChange?: () => void;
42
+ setText: (text: string) => void;
43
+ getText: () => string;
44
+ render: (width: number) => string[];
45
+ handleInput: (data: string) => void;
46
+ };
47
+ Key: {
48
+ enter: string;
49
+ tab: string;
50
+ escape: string;
51
+ up: string;
52
+ down: string;
53
+ ctrl: (key: string) => string;
54
+ shift: (key: string) => string;
55
+ };
56
+ matchesKey: (input: string, key: string) => boolean;
57
+ truncateToWidth: (text: string, width: number) => string;
58
+ visibleWidth: (text: string) => number;
59
+ wrapTextWithAnsi: (text: string, width: number) => string[];
60
+ };
61
+ }
62
+
63
+ export interface QnAOption {
64
+ label: string;
65
+ description: string;
66
+ }
67
+
68
+ export interface QnAQuestion {
69
+ header?: string;
70
+ question: string;
71
+ context?: string;
72
+ options?: QnAOption[];
73
+ }
74
+
75
+ export interface QnATemplate {
76
+ label: string;
77
+ template: string;
78
+ }
79
+
80
+ export interface QnAResponse {
81
+ selectedOptionIndex: number;
82
+ customText: string;
83
+ selectionTouched: boolean;
84
+ committed: boolean;
85
+ }
86
+
87
+ export interface QnAResult {
88
+ text: string;
89
+ answers: string[];
90
+ responses: QnAResponse[];
91
+ }
92
+
93
+ export interface QnATemplateData {
94
+ question: string;
95
+ context?: string;
96
+ answer: string;
97
+ index: number;
98
+ total: number;
99
+ }
100
+
101
+ export function getQuestionOptions(question: QnAQuestion): QnAOption[] {
102
+ return question.options ?? [];
103
+ }
104
+
105
+ export function formatResponseAnswer(question: QnAQuestion, response: QnAResponse): string {
106
+ const options = getQuestionOptions(question);
107
+ if (options.length === 0) {
108
+ return response.customText;
109
+ }
110
+
111
+ const otherIndex = options.length;
112
+ if (response.selectedOptionIndex === otherIndex) {
113
+ return response.customText;
114
+ }
115
+
116
+ if (!response.selectionTouched) {
117
+ return "";
118
+ }
119
+
120
+ return options[response.selectedOptionIndex]?.label ?? "";
121
+ }
122
+
123
+ export function normalizeResponseForQuestion(
124
+ question: QnAQuestion,
125
+ response: Partial<QnAResponse> | undefined,
126
+ fallbackAnswer: string | undefined,
127
+ inferCommittedFromContent: boolean,
128
+ ): QnAResponse {
129
+ const options = getQuestionOptions(question);
130
+ const rawFallback = fallbackAnswer ?? "";
131
+ const rawCustomText = response?.customText ?? rawFallback;
132
+ let selectedOptionIndex =
133
+ typeof response?.selectedOptionIndex === "number" && Number.isFinite(response.selectedOptionIndex)
134
+ ? Math.trunc(response.selectedOptionIndex)
135
+ : undefined;
136
+ let selectionTouched = response?.selectionTouched ?? false;
137
+
138
+ if (options.length === 0) {
139
+ selectedOptionIndex = 0;
140
+ if (response?.selectionTouched === undefined && rawCustomText.trim().length > 0) {
141
+ selectionTouched = true;
142
+ }
143
+ } else if (selectedOptionIndex === undefined) {
144
+ const fallbackTrimmed = rawFallback.trim();
145
+ if (fallbackTrimmed.length === 0) {
146
+ selectedOptionIndex = 0;
147
+ if (response?.selectionTouched === undefined) {
148
+ selectionTouched = false;
149
+ }
150
+ } else {
151
+ const optionIndex = options.findIndex((option) => option.label === fallbackTrimmed);
152
+ selectedOptionIndex = optionIndex >= 0 ? optionIndex : options.length;
153
+ if (response?.selectionTouched === undefined) {
154
+ selectionTouched = true;
155
+ }
156
+ }
157
+ } else if (response?.selectionTouched === undefined) {
158
+ selectionTouched = response?.committed === true;
159
+ if (!selectionTouched) {
160
+ const fallbackTrimmed = rawFallback.trim();
161
+ if (fallbackTrimmed.length > 0) {
162
+ const optionIndex = options.findIndex((option) => option.label === fallbackTrimmed);
163
+ if (optionIndex >= 0) {
164
+ selectionTouched = optionIndex === selectedOptionIndex && optionIndex !== 0;
165
+ } else {
166
+ selectionTouched = selectedOptionIndex === options.length;
167
+ }
168
+ }
169
+ }
170
+ }
171
+
172
+ const maxIndex = options.length;
173
+ const normalizedIndex = Math.max(0, Math.min(maxIndex, selectedOptionIndex ?? 0));
174
+ const useCustomText = options.length === 0 || normalizedIndex === options.length;
175
+ const normalizedCustomText = useCustomText ? rawCustomText : "";
176
+
177
+ let committed = response?.committed ?? false;
178
+ if (response?.committed === undefined && inferCommittedFromContent) {
179
+ committed = formatResponseAnswer(question, {
180
+ selectedOptionIndex: normalizedIndex,
181
+ customText: normalizedCustomText,
182
+ selectionTouched,
183
+ committed: false,
184
+ }).trim().length > 0;
185
+ }
186
+
187
+ return {
188
+ selectedOptionIndex: normalizedIndex,
189
+ customText: normalizedCustomText,
190
+ selectionTouched,
191
+ committed,
192
+ };
193
+ }
194
+
195
+ export function normalizeResponses(
196
+ questions: QnAQuestion[],
197
+ responses: Array<Partial<QnAResponse>> | undefined,
198
+ fallbackAnswers: string[] | undefined,
199
+ inferCommittedFromContent: boolean,
200
+ ): QnAResponse[] {
201
+ return questions.map((question, index) =>
202
+ normalizeResponseForQuestion(
203
+ question,
204
+ responses?.[index],
205
+ fallbackAnswers?.[index],
206
+ inferCommittedFromContent,
207
+ ),
208
+ );
209
+ }
210
+
211
+ export function cloneResponses(responses: QnAResponse[]): QnAResponse[] {
212
+ return responses.map((response) => ({ ...response }));
213
+ }
214
+
215
+ export function deriveAnswersFromResponses(questions: QnAQuestion[], responses: QnAResponse[]): string[] {
216
+ return questions.map((question, index) => formatResponseAnswer(question, responses[index]));
217
+ }
218
+
219
+ export function hasResponseContent(question: QnAQuestion, response: QnAResponse): boolean {
220
+ return formatResponseAnswer(question, response).trim().length > 0;
221
+ }
222
+
223
+ function defaultResolveNumericShortcut(
224
+ input: string,
225
+ maxOptionIndex: number,
226
+ usingCustomEditor: boolean,
227
+ ): number | null {
228
+ if (usingCustomEditor) {
229
+ return null;
230
+ }
231
+
232
+ if (!/^[1-9]$/.test(input)) {
233
+ return null;
234
+ }
235
+
236
+ const selectedIndex = Number(input) - 1;
237
+ if (selectedIndex > maxOptionIndex) {
238
+ return null;
239
+ }
240
+
241
+ return selectedIndex;
242
+ }
243
+
244
+ function defaultApplyTemplate(template: string, data: QnATemplateData): string {
245
+ const replacements: Record<string, string> = {
246
+ question: data.question,
247
+ context: data.context ?? "",
248
+ answer: data.answer,
249
+ index: String(data.index + 1),
250
+ total: String(data.total),
251
+ };
252
+
253
+ return template.replace(/\{\{(question|context|answer|index|total)\}\}/g, (_match, key: string) => {
254
+ return replacements[key] ?? "";
255
+ });
256
+ }
257
+
258
+ function summarizeAnswer(text: string, maxLength: number = 60): string {
259
+ const singleLine = text.replace(/\s+/g, " ").trim();
260
+ if (singleLine.length <= maxLength) {
261
+ return singleLine;
262
+ }
263
+ return `${singleLine.slice(0, maxLength - 1)}…`;
264
+ }
265
+
266
+ export class QnATuiComponent<TQuestion extends QnAQuestion> implements Component {
267
+ private questions: TQuestion[];
268
+ private responses: QnAResponse[];
269
+ private currentIndex = 0;
270
+ private editor: {
271
+ disableSubmit?: boolean;
272
+ onChange?: () => void;
273
+ setText: (text: string) => void;
274
+ getText: () => string;
275
+ render: (width: number) => string[];
276
+ handleInput: (data: string) => void;
277
+ };
278
+ private tui: TUI;
279
+ private onDone: (result: QnAResult | null) => void;
280
+ private showingConfirmation = false;
281
+ private templates: QnATemplate[];
282
+ private templateIndex = 0;
283
+ private onResponsesChange?: (responses: QnAResponse[]) => void;
284
+ private title: string;
285
+ private resolveNumericShortcut: (
286
+ input: string,
287
+ maxOptionIndex: number,
288
+ usingCustomEditor: boolean,
289
+ ) => number | null;
290
+ private applyTemplate: (template: string, data: QnATemplateData) => string;
291
+ private questionSummaryLabel: (question: TQuestion, index: number) => string;
292
+
293
+ private cachedWidth?: number;
294
+ private cachedLines?: string[];
295
+
296
+ private dim = (s: string) => s;
297
+ private bold = (s: string) => s;
298
+ private italic = (s: string) => `\x1b[3m${s}\x1b[0m`;
299
+ private cyan = (s: string) => s;
300
+ private green = (s: string) => s;
301
+ private yellow = (s: string) => s;
302
+ private gray = (s: string) => s;
303
+
304
+ constructor(
305
+ questions: TQuestion[],
306
+ tui: TUI,
307
+ onDone: (result: QnAResult | null) => void,
308
+ options?: {
309
+ title?: string;
310
+ templates?: QnATemplate[];
311
+ initialResponses?: Array<Partial<QnAResponse>>;
312
+ fallbackAnswers?: string[];
313
+ inferCommittedFromContent?: boolean;
314
+ onResponsesChange?: (responses: QnAResponse[]) => void;
315
+ resolveNumericShortcut?: (
316
+ input: string,
317
+ maxOptionIndex: number,
318
+ usingCustomEditor: boolean,
319
+ ) => number | null;
320
+ applyTemplate?: (template: string, data: QnATemplateData) => string;
321
+ questionSummaryLabel?: (question: TQuestion, index: number) => string;
322
+ accentColor?: (text: string) => string;
323
+ successColor?: (text: string) => string;
324
+ warningColor?: (text: string) => string;
325
+ mutedColor?: (text: string) => string;
326
+ dimColor?: (text: string) => string;
327
+ boldText?: (text: string) => string;
328
+ italicText?: (text: string) => string;
329
+ },
330
+ ) {
331
+ this.questions = questions;
332
+ this.templates = options?.templates ?? [];
333
+ this.responses = normalizeResponses(
334
+ questions,
335
+ options?.initialResponses,
336
+ options?.fallbackAnswers,
337
+ options?.inferCommittedFromContent ?? false,
338
+ );
339
+ this.tui = tui;
340
+ this.onDone = onDone;
341
+ this.onResponsesChange = options?.onResponsesChange;
342
+ this.title = options?.title ?? "Questions";
343
+ this.resolveNumericShortcut = options?.resolveNumericShortcut ?? defaultResolveNumericShortcut;
344
+ this.applyTemplate = options?.applyTemplate ?? defaultApplyTemplate;
345
+ this.questionSummaryLabel =
346
+ options?.questionSummaryLabel ??
347
+ ((question) => {
348
+ return question.header?.trim() || question.question;
349
+ });
350
+ this.cyan = options?.accentColor ?? this.cyan;
351
+ this.green = options?.successColor ?? this.green;
352
+ this.yellow = options?.warningColor ?? this.yellow;
353
+ this.gray = options?.mutedColor ?? this.gray;
354
+ this.dim = options?.dimColor ?? this.dim;
355
+ this.bold = options?.boldText ?? this.bold;
356
+ this.italic = options?.italicText ?? this.italic;
357
+
358
+ const editorTheme: EditorTheme = {
359
+ borderColor: this.dim,
360
+ selectList: {
361
+ matchHighlight: this.cyan,
362
+ itemSecondary: this.gray,
363
+ },
364
+ };
365
+
366
+ const { Editor } = getPiTui();
367
+ this.editor = new Editor(tui, editorTheme);
368
+ this.editor.disableSubmit = true;
369
+ this.editor.onChange = () => {
370
+ this.saveCurrentResponse();
371
+ this.invalidate();
372
+ this.tui.requestRender();
373
+ };
374
+
375
+ this.loadEditorForCurrentQuestion();
376
+ }
377
+
378
+ private getCurrentQuestion(): TQuestion {
379
+ return this.questions[this.currentIndex];
380
+ }
381
+
382
+ private isPrintableInput(data: string): boolean {
383
+ if (data.length !== 1) {
384
+ return false;
385
+ }
386
+
387
+ const code = data.charCodeAt(0);
388
+ return code >= 32 && code !== 127;
389
+ }
390
+
391
+ private shouldUseEditor(index: number = this.currentIndex): boolean {
392
+ const question = this.questions[index];
393
+ const options = getQuestionOptions(question);
394
+ if (options.length === 0) {
395
+ return true;
396
+ }
397
+
398
+ return this.responses[index].selectedOptionIndex === options.length;
399
+ }
400
+
401
+ private getCurrentAnswerText(): string {
402
+ const question = this.getCurrentQuestion();
403
+ const response = this.responses[this.currentIndex];
404
+ return formatResponseAnswer(question, response);
405
+ }
406
+
407
+ private getAnswerText(index: number): string {
408
+ return formatResponseAnswer(this.questions[index], this.responses[index]);
409
+ }
410
+
411
+ private emitResponseChange(): void {
412
+ this.onResponsesChange?.(cloneResponses(this.responses));
413
+ }
414
+
415
+ private loadEditorForCurrentQuestion(): void {
416
+ if (!this.shouldUseEditor()) {
417
+ this.editor.setText("");
418
+ return;
419
+ }
420
+
421
+ this.editor.setText(this.responses[this.currentIndex].customText ?? "");
422
+ }
423
+
424
+ private saveCurrentResponse(emit: boolean = true): void {
425
+ if (this.shouldUseEditor()) {
426
+ const text = this.editor.getText();
427
+ this.responses[this.currentIndex].customText = text;
428
+ const question = this.questions[this.currentIndex];
429
+ if (getQuestionOptions(question).length === 0 || text.trim().length > 0) {
430
+ this.responses[this.currentIndex].selectionTouched = true;
431
+ }
432
+ }
433
+
434
+ if (emit) {
435
+ this.emitResponseChange();
436
+ }
437
+ }
438
+
439
+ private navigateTo(index: number): void {
440
+ if (index < 0 || index >= this.questions.length) {
441
+ return;
442
+ }
443
+
444
+ this.saveCurrentResponse();
445
+ this.currentIndex = index;
446
+ this.showingConfirmation = false;
447
+ this.loadEditorForCurrentQuestion();
448
+ this.invalidate();
449
+ }
450
+
451
+ private selectOption(index: number): void {
452
+ const question = this.getCurrentQuestion();
453
+ const options = getQuestionOptions(question);
454
+ if (options.length === 0) {
455
+ return;
456
+ }
457
+
458
+ const maxIndex = options.length;
459
+ const normalized = Math.max(0, Math.min(maxIndex, index));
460
+ const currentResponse = this.responses[this.currentIndex];
461
+ if (normalized === currentResponse.selectedOptionIndex && currentResponse.selectionTouched) {
462
+ return;
463
+ }
464
+
465
+ this.saveCurrentResponse(false);
466
+ currentResponse.selectedOptionIndex = normalized;
467
+ currentResponse.selectionTouched = true;
468
+ this.loadEditorForCurrentQuestion();
469
+ this.emitResponseChange();
470
+ this.invalidate();
471
+ this.tui.requestRender();
472
+ }
473
+
474
+ private applyNextTemplate(): void {
475
+ if (this.templates.length === 0) {
476
+ return;
477
+ }
478
+
479
+ const question = this.getCurrentQuestion();
480
+ const options = getQuestionOptions(question);
481
+ if (options.length > 0 && !this.shouldUseEditor()) {
482
+ this.selectOption(options.length);
483
+ }
484
+
485
+ const template = this.templates[this.templateIndex];
486
+ const updated = this.applyTemplate(template.template, {
487
+ question: question.question,
488
+ context: question.context,
489
+ answer: this.getCurrentAnswerText(),
490
+ index: this.currentIndex,
491
+ total: this.questions.length,
492
+ });
493
+
494
+ this.editor.setText(updated);
495
+ this.saveCurrentResponse();
496
+ this.templateIndex = (this.templateIndex + 1) % this.templates.length;
497
+ this.invalidate();
498
+ this.tui.requestRender();
499
+ }
500
+
501
+ private submit(): void {
502
+ this.saveCurrentResponse();
503
+
504
+ const answers = deriveAnswersFromResponses(this.questions, this.responses);
505
+ const parts: string[] = [];
506
+ for (let i = 0; i < this.questions.length; i++) {
507
+ const question = this.questions[i];
508
+ const rawAnswer = answers[i] ?? "";
509
+ if (rawAnswer.trim().length === 0) {
510
+ continue;
511
+ }
512
+
513
+ parts.push(`Q: ${question.question}`);
514
+ parts.push(`A: ${rawAnswer}`);
515
+ parts.push("");
516
+ }
517
+
518
+ this.onDone({
519
+ text: parts.join("\n").trim(),
520
+ answers,
521
+ responses: cloneResponses(this.responses),
522
+ });
523
+ }
524
+
525
+ private cancel(): void {
526
+ this.onDone(null);
527
+ }
528
+
529
+ invalidate(): void {
530
+ this.cachedWidth = undefined;
531
+ this.cachedLines = undefined;
532
+ }
533
+
534
+ handleInput(data: string): void {
535
+ const { Key, matchesKey } = getPiTui();
536
+
537
+ if (this.showingConfirmation) {
538
+ if (matchesKey(data, Key.enter)) {
539
+ this.submit();
540
+ return;
541
+ }
542
+ if (matchesKey(data, Key.ctrl("c"))) {
543
+ this.cancel();
544
+ return;
545
+ }
546
+ if (matchesKey(data, Key.escape)) {
547
+ this.showingConfirmation = false;
548
+ this.invalidate();
549
+ this.tui.requestRender();
550
+ return;
551
+ }
552
+ return;
553
+ }
554
+
555
+ if (matchesKey(data, Key.ctrl("c"))) {
556
+ this.cancel();
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 paddedContent = " ".repeat(leftPad) + content;
657
+ const contentLen = visibleWidth(paddedContent);
658
+ const rightPad = Math.max(0, boxWidth - contentLen - 2);
659
+ return this.dim("│") + paddedContent + " ".repeat(rightPad) + this.dim("│");
660
+ };
661
+
662
+ const emptyBoxLine = (): string => {
663
+ return this.dim("│") + " ".repeat(boxWidth - 2) + this.dim("│");
664
+ };
665
+
666
+ const padToWidth = (line: string): string => {
667
+ const len = visibleWidth(line);
668
+ return line + " ".repeat(Math.max(0, width - len));
669
+ };
670
+
671
+ const question = this.getCurrentQuestion();
672
+ const response = this.responses[this.currentIndex];
673
+ const options = getQuestionOptions(question);
674
+ const usesEditor = this.shouldUseEditor();
675
+
676
+ lines.push(padToWidth(this.dim(`╭${horizontalLine(boxWidth - 2)}╮`)));
677
+ const title = `${this.title} ${this.dim(`(${this.currentIndex + 1}/${this.questions.length})`)}`;
678
+ lines.push(padToWidth(boxLine(title)));
679
+ lines.push(padToWidth(this.dim(`├${horizontalLine(boxWidth - 2)}┤`)));
680
+
681
+ const progressParts: string[] = [];
682
+ for (let i = 0; i < this.questions.length; i++) {
683
+ const current = i === this.currentIndex;
684
+ const answered = hasResponseContent(this.questions[i], this.responses[i]);
685
+ if (current) {
686
+ progressParts.push(this.cyan("●"));
687
+ } else if (answered) {
688
+ progressParts.push(this.green("●"));
689
+ } else {
690
+ progressParts.push(this.dim("○"));
691
+ }
692
+ }
693
+ lines.push(padToWidth(boxLine(progressParts.join(" "))));
694
+
695
+ if (!this.showingConfirmation) {
696
+ if (question.header) {
697
+ lines.push(padToWidth(boxLine(this.cyan(question.header))));
698
+ }
699
+ lines.push(padToWidth(emptyBoxLine()));
700
+
701
+ const wrappedQuestion = wrapTextWithAnsi(`${this.bold("Q:")} ${this.bold(question.question)}`, contentWidth);
702
+ for (const line of wrappedQuestion) {
703
+ lines.push(padToWidth(boxLine(line)));
704
+ }
705
+
706
+ if (question.context) {
707
+ lines.push(padToWidth(emptyBoxLine()));
708
+ for (const line of wrapTextWithAnsi(this.gray(`> ${question.context}`), contentWidth - 2)) {
709
+ lines.push(padToWidth(boxLine(line)));
710
+ }
711
+ }
712
+
713
+ if (options.length > 0) {
714
+ lines.push(padToWidth(emptyBoxLine()));
715
+ for (let i = 0; i <= options.length; i++) {
716
+ const isOther = i === options.length;
717
+ const optionLabel = isOther ? "Other" : options[i].label;
718
+ const description = isOther ? "Type your own answer" : options[i].description;
719
+ const selected = response.selectedOptionIndex === i;
720
+ const marker = selected ? "▶" : " ";
721
+ const optionPrefix = `${marker} ${i + 1}. `;
722
+ const line = `${optionPrefix}${optionLabel}`;
723
+ const styledLine = selected
724
+ ? response.selectionTouched
725
+ ? this.green(line)
726
+ : this.cyan(line)
727
+ : line;
728
+ lines.push(padToWidth(boxLine(truncateToWidth(styledLine, contentWidth))));
729
+
730
+ if (selected && description && description.trim().length > 0) {
731
+ const descriptionIndent = " ".repeat(visibleWidth(optionPrefix));
732
+ const wrappedDescription = wrapTextWithAnsi(
733
+ description,
734
+ Math.max(10, contentWidth - visibleWidth(descriptionIndent)),
735
+ );
736
+ for (const wrapped of wrappedDescription) {
737
+ lines.push(padToWidth(boxLine(`${descriptionIndent}${this.gray(wrapped)}`)));
738
+ }
739
+ }
740
+ }
741
+ }
742
+
743
+ lines.push(padToWidth(emptyBoxLine()));
744
+ if (usesEditor) {
745
+ const answerPrefix = this.bold("A: ");
746
+ const editorWidth = Math.max(20, contentWidth - 7);
747
+ const editorLines = this.editor.render(editorWidth);
748
+ for (let i = 1; i < editorLines.length - 1; i++) {
749
+ if (i === 1) {
750
+ lines.push(padToWidth(boxLine(answerPrefix + editorLines[i])));
751
+ } else {
752
+ lines.push(padToWidth(boxLine(" " + editorLines[i])));
753
+ }
754
+ }
755
+ } else {
756
+ const selectedLabel = response.selectionTouched
757
+ ? options[response.selectedOptionIndex]?.label ?? ""
758
+ : this.dim("(select an option)");
759
+ lines.push(padToWidth(boxLine(`${this.bold("A:")} ${selectedLabel}`)));
760
+ }
761
+ lines.push(padToWidth(emptyBoxLine()));
762
+ }
763
+
764
+ if (this.showingConfirmation) {
765
+ lines.push(padToWidth(this.dim(`├${horizontalLine(boxWidth - 2)}┤`)));
766
+ lines.push(padToWidth(boxLine(this.bold("Review before submit:"))));
767
+ for (let i = 0; i < this.questions.length; i++) {
768
+ const summaryLabel = this.questionSummaryLabel(this.questions[i], i);
769
+ const answerText = this.getAnswerText(i);
770
+ const hasAnswer = answerText.trim().length > 0;
771
+ const answerPreview = hasAnswer
772
+ ? this.green(summarizeAnswer(answerText))
773
+ : this.yellow("(no answer)");
774
+ const questionLine = `${this.bold(`${i + 1}.`)} ${this.cyan(summaryLabel)}`;
775
+ const answerLine = ` ${this.dim("Answer:")} ${answerPreview}`;
776
+ lines.push(padToWidth(boxLine(truncateToWidth(questionLine, contentWidth))));
777
+ lines.push(padToWidth(boxLine(truncateToWidth(answerLine, contentWidth))));
778
+ }
779
+ lines.push(padToWidth(emptyBoxLine()));
780
+ const confirmMsg = `${this.yellow("Submit all answers?")} ${this.dim("(Enter submit, Esc keep editing)")}`;
781
+ lines.push(padToWidth(boxLine(truncateToWidth(confirmMsg, contentWidth))));
782
+ const separator = this.cyan(" · ");
783
+ const formatHint = (shortcut: string, action: string) => `${this.bold(shortcut)} ${this.italic(action)}`;
784
+ const confirmControls = `${formatHint("Enter", "submit")}${separator}${formatHint("Esc", "back")}${separator}${formatHint("Ctrl+C", "cancel")}`;
785
+ lines.push(padToWidth(boxLine(truncateToWidth(confirmControls, contentWidth))));
786
+ } else {
787
+ lines.push(padToWidth(this.dim(`├${horizontalLine(boxWidth - 2)}┤`)));
788
+
789
+ const separator = this.cyan(" · ");
790
+ const formatHint = (shortcut: string, action: string) => `${this.bold(shortcut)} ${this.italic(action)}`;
791
+ const joinHints = (parts: string[]) => parts.join(separator);
792
+ const canFit = (parts: string[]) => visibleWidth(joinHints(parts)) <= contentWidth;
793
+
794
+ const tabHint = formatHint("Tab/⇧Tab", "next/prev");
795
+ const enterHint = formatHint("Enter", "commit + next");
796
+ const cancelHint = formatHint("Ctrl+C", "cancel");
797
+
798
+ const optionalHints: string[] = [];
799
+ if (options.length > 0 && !usesEditor) {
800
+ optionalHints.push(formatHint("↑/↓/1-9", "pick option"));
801
+ }
802
+ if (usesEditor) {
803
+ optionalHints.push(formatHint("⇧Enter", "newline"));
804
+ }
805
+ if (this.templates.length > 0) {
806
+ optionalHints.push(formatHint("Ctrl+T", "template"));
807
+ }
808
+
809
+ const trailingHints = [enterHint, tabHint, cancelHint];
810
+ const controls: string[] = [];
811
+ for (const hint of optionalHints) {
812
+ if (canFit([...controls, hint, ...trailingHints])) {
813
+ controls.push(hint);
814
+ }
815
+ }
816
+ controls.push(...trailingHints);
817
+
818
+ lines.push(padToWidth(boxLine(truncateToWidth(joinHints(controls), contentWidth))));
819
+ }
820
+ lines.push(padToWidth(this.dim(`╰${horizontalLine(boxWidth - 2)}╯`)));
821
+
822
+ this.cachedWidth = width;
823
+ this.cachedLines = lines;
824
+ return lines;
825
+ }
826
+ }