forked from edlsh/pi-ask-user
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
1549 lines (1332 loc) · 53.4 KB
/
index.ts
File metadata and controls
1549 lines (1332 loc) · 53.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Ask Tool Extension - Interactive question UI for pi-coding-agent
*
* Refactored to use built-in TUI primitives (Container/Text/Spacer/SelectList/Editor)
* and a custom box border instead of manual ANSI box drawing.
*/
import type { ExtensionAPI, Theme } from "@mariozechner/pi-coding-agent";
import { getMarkdownTheme } from "@mariozechner/pi-coding-agent";
import { Type } from "@sinclair/typebox";
import {
Container,
type Component,
decodeKittyPrintable,
Editor,
type EditorTheme,
fuzzyFilter,
Key,
type Keybinding,
type KeybindingsManager,
Markdown,
type MarkdownTheme,
matchesKey,
Spacer,
Text,
type TUI,
truncateToWidth,
wrapTextWithAnsi,
} from "@mariozechner/pi-tui";
import { renderSingleSelectRows } from "./single-select-layout";
import { createRequire } from "node:module";
const _require = createRequire(import.meta.url);
const ASK_USER_VERSION: string = (_require("./package.json") as { version: string }).version;
type AskOptionInput = QuestionOption | string;
interface AskParams {
question: string;
context?: string;
options?: AskOptionInput[];
allowMultiple?: boolean;
allowFreeform?: boolean;
allowComment?: boolean;
timeout?: number;
}
type AskResponse =
| {
kind: "selection";
selections: string[];
comment?: string;
}
| {
kind: "freeform";
text: string;
};
interface AskToolDetails {
question: string;
context?: string;
options: QuestionOption[];
response: AskResponse | null;
cancelled: boolean;
}
type AskUIResult = AskResponse;
function normalizeOptions(options: AskOptionInput[]): QuestionOption[] {
return options
.map((option) => {
if (typeof option === "string") {
return { title: option };
}
if (option && typeof option === "object" && typeof option.title === "string") {
return { title: option.title, description: option.description };
}
return null;
})
.filter((option): option is QuestionOption => option !== null);
}
function formatOptionsForMessage(options: QuestionOption[]): string {
return options
.map((option, index) => {
const desc = option.description ? ` — ${option.description}` : "";
return `${index + 1}. ${option.title}${desc}`;
})
.join("\n");
}
function normalizeOptionalComment(text: string | null | undefined): string | undefined {
const trimmed = text?.trim();
return trimmed ? trimmed : undefined;
}
function createFreeformResponse(text: string | null | undefined): AskResponse | null {
const trimmed = text?.trim();
return trimmed ? { kind: "freeform", text: trimmed } : null;
}
function createSelectionResponse(selections: string[], comment?: string | null): AskResponse | null {
const normalizedSelections = selections.map((selection) => selection.trim()).filter(Boolean);
if (normalizedSelections.length === 0) return null;
const normalizedComment = normalizeOptionalComment(comment);
return normalizedComment
? { kind: "selection", selections: normalizedSelections, comment: normalizedComment }
: { kind: "selection", selections: normalizedSelections };
}
function formatResponseSummary(response: AskResponse): string {
if (response.kind === "freeform") return response.text;
const selections = response.selections.join(", ");
return response.comment ? `${selections} — ${response.comment}` : selections;
}
function buildCommentPrompt(prompt: string, selections: string[]): string {
const label = selections.length === 1 ? "Selected option" : "Selected options";
const lines = selections.map((selection) => `- ${selection}`).join("\n");
return `${prompt}\n\n${label}:\n${lines}`;
}
function parseDialogSelections(input: string): string[] {
return input
.split(",")
.map((selection) => selection.trim())
.filter(Boolean);
}
function isCancelledInput(value: unknown): value is null | undefined {
return value === null || value === undefined;
}
function isSelectionResponse(response: AskResponse): response is Extract<AskResponse, { kind: "selection" }> {
return response.kind === "selection";
}
function createSelectListTheme(theme: Theme) {
return {
selectedPrefix: (t: string) => theme.fg("accent", t),
selectedText: (t: string) => theme.fg("accent", t),
description: (t: string) => theme.fg("muted", t),
scrollInfo: (t: string) => theme.fg("dim", t),
noMatch: (t: string) => theme.fg("warning", t),
};
}
function createEditorTheme(theme: Theme): EditorTheme {
return {
borderColor: (s: string) => theme.fg("accent", s),
selectList: createSelectListTheme(theme),
};
}
const BOX_BORDER_LEFT = "│ ";
const BOX_BORDER_RIGHT = " │";
const BOX_BORDER_OVERHEAD = BOX_BORDER_LEFT.length + BOX_BORDER_RIGHT.length;
class BoxBorderTop implements Component {
private color: (s: string) => string;
private title?: string;
private titleColor?: (s: string) => string;
constructor(color: (s: string) => string, title?: string, titleColor?: (s: string) => string) {
this.color = color;
this.title = title;
this.titleColor = titleColor;
}
invalidate(): void { }
render(width: number): string[] {
const inner = Math.max(0, width - 2);
if (!this.title || inner < this.title.length + 4) {
return [this.color(`╭${"─".repeat(inner)}╮`)];
}
const label = ` ${this.title} `;
const remaining = inner - 1 - label.length;
const titleStyle = this.titleColor ?? this.color;
return [
this.color("╭─") + titleStyle(label) + this.color("─".repeat(Math.max(0, remaining)) + "╮"),
];
}
}
class BoxBorderBottom implements Component {
private color: (s: string) => string;
private label?: string;
private labelColor?: (s: string) => string;
constructor(color: (s: string) => string, label?: string, labelColor?: (s: string) => string) {
this.color = color;
this.label = label;
this.labelColor = labelColor;
}
invalidate(): void { }
render(width: number): string[] {
const inner = Math.max(0, width - 2);
if (!this.label || inner < this.label.length + 4) {
return [this.color(`╰${"─".repeat(inner)}╯`)];
}
const tag = ` ${this.label} `;
const leftDashes = inner - tag.length - 1;
const style = this.labelColor ?? this.color;
return [
this.color("╰" + "─".repeat(Math.max(0, leftDashes))) + style(tag) + this.color("─╯"),
];
}
}
function formatKeyList(keys: string[]): string {
return keys.join("/");
}
function keybindingHint(
theme: Theme,
keybindings: KeybindingsManager,
keybinding: Keybinding,
description: string,
): string {
return `${theme.fg("dim", formatKeyList(keybindings.getKeys(keybinding)))}${theme.fg("muted", ` ${description}`)}`;
}
function literalHint(theme: Theme, key: string, description: string): string {
return `${theme.fg("dim", key)}${theme.fg("muted", ` ${description}`)}`;
}
function isCommentToggleKey(data: string): boolean {
return matchesKey(data, Key.ctrl("g"));
}
type AskMode = "select" | "freeform" | "comment";
const ASK_OVERLAY_MAX_HEIGHT_RATIO = 0.85;
const ASK_OVERLAY_WIDTH = "92%";
const ASK_OVERLAY_MIN_WIDTH = 40;
const SINGLE_SELECT_SPLIT_PANE_MIN_WIDTH = 84;
const SINGLE_SELECT_SPLIT_PANE_LEFT_MIN_WIDTH = 32;
const SINGLE_SELECT_SPLIT_PANE_RIGHT_MIN_WIDTH = 28;
const SINGLE_SELECT_SPLIT_PANE_SEPARATOR = " │ ";
const FREEFORM_SENTINEL = "\u270f\ufe0f Type custom response...";
const COMMENT_TOGGLE_LABEL = "Add extra context after selection";
class MultiSelectList implements Component {
private options: QuestionOption[];
private allowFreeform: boolean;
private allowComment: boolean;
private theme: Theme;
private keybindings: KeybindingsManager;
private selectedIndex = 0;
private checked = new Set<number>();
private commentEnabled = false;
private cachedWidth?: number;
private cachedLines?: string[];
public onCancel?: () => void;
public onSubmit?: (result: string[]) => void;
public onEnterFreeform?: () => void;
constructor(
options: QuestionOption[],
allowFreeform: boolean,
allowComment: boolean,
theme: Theme,
keybindings: KeybindingsManager,
) {
this.options = options;
this.allowFreeform = allowFreeform;
this.allowComment = allowComment;
this.theme = theme;
this.keybindings = keybindings;
}
public isCommentEnabled(): boolean {
return this.commentEnabled;
}
invalidate(): void {
this.cachedWidth = undefined;
this.cachedLines = undefined;
}
private getItemCount(): number {
return this.options.length + (this.allowComment ? 1 : 0) + (this.allowFreeform ? 1 : 0);
}
private getCommentToggleIndex(): number | null {
return this.allowComment ? this.options.length : null;
}
private getFreeformIndex(): number {
return this.options.length + (this.allowComment ? 1 : 0);
}
private isCommentToggleRow(index: number): boolean {
const toggleIndex = this.getCommentToggleIndex();
return toggleIndex !== null && index === toggleIndex;
}
private isFreeformRow(index: number): boolean {
return this.allowFreeform && index === this.getFreeformIndex();
}
private toggle(index: number): void {
if (index < 0 || index >= this.options.length) return;
if (this.checked.has(index)) this.checked.delete(index);
else this.checked.add(index);
}
private toggleComment(): void {
if (!this.allowComment) return;
this.commentEnabled = !this.commentEnabled;
this.invalidate();
}
handleInput(data: string): void {
if (this.keybindings.matches(data, "tui.select.cancel")) {
this.onCancel?.();
return;
}
const count = this.getItemCount();
if (count === 0) {
this.onCancel?.();
return;
}
if (this.allowComment && isCommentToggleKey(data)) {
this.toggleComment();
return;
}
if (this.keybindings.matches(data, "tui.select.up") || matchesKey(data, Key.shift("tab"))) {
this.selectedIndex = this.selectedIndex === 0 ? count - 1 : this.selectedIndex - 1;
this.invalidate();
return;
}
if (this.keybindings.matches(data, "tui.select.down") || matchesKey(data, Key.tab)) {
this.selectedIndex = this.selectedIndex === count - 1 ? 0 : this.selectedIndex + 1;
this.invalidate();
return;
}
const numMatch = data.match(/^[1-9]$/);
if (numMatch) {
const idx = Number.parseInt(numMatch[0], 10) - 1;
if (idx >= 0 && idx < this.options.length) {
this.toggle(idx);
this.selectedIndex = Math.min(idx, count - 1);
this.invalidate();
}
return;
}
if (matchesKey(data, Key.space)) {
if (this.isCommentToggleRow(this.selectedIndex)) {
this.toggleComment();
return;
}
if (this.isFreeformRow(this.selectedIndex)) {
this.onEnterFreeform?.();
return;
}
this.toggle(this.selectedIndex);
this.invalidate();
return;
}
if (this.keybindings.matches(data, "tui.select.confirm")) {
if (this.isCommentToggleRow(this.selectedIndex)) {
this.toggleComment();
return;
}
if (this.isFreeformRow(this.selectedIndex)) {
this.onEnterFreeform?.();
return;
}
const selectedTitles = Array.from(this.checked)
.sort((a, b) => a - b)
.map((i) => this.options[i]?.title)
.filter((t): t is string => !!t);
const fallback = this.options[this.selectedIndex]?.title;
const result = selectedTitles.length > 0 ? selectedTitles : fallback ? [fallback] : [];
if (result.length > 0) this.onSubmit?.(result);
else this.onCancel?.();
}
}
render(width: number): string[] {
if (this.cachedLines && this.cachedWidth === width) {
return this.cachedLines;
}
const theme = this.theme;
const count = this.getItemCount();
const maxVisible = Math.min(count, 10);
if (count === 0) {
this.cachedLines = [theme.fg("warning", "No options")];
this.cachedWidth = width;
return this.cachedLines;
}
const startIndex = Math.max(0, Math.min(this.selectedIndex - Math.floor(maxVisible / 2), count - maxVisible));
const endIndex = Math.min(startIndex + maxVisible, count);
const lines: string[] = [];
for (let i = startIndex; i < endIndex; i++) {
const isSelected = i === this.selectedIndex;
const prefix = isSelected ? theme.fg("accent", "→") : " ";
if (this.isCommentToggleRow(i)) {
const checkbox = this.commentEnabled ? theme.fg("success", "[✓]") : theme.fg("dim", "[ ]");
const label = isSelected
? theme.fg("accent", theme.bold(COMMENT_TOGGLE_LABEL))
: theme.fg("text", theme.bold(COMMENT_TOGGLE_LABEL));
lines.push(truncateToWidth(`${prefix} ${checkbox} ${label}`, width, ""));
continue;
}
if (this.isFreeformRow(i)) {
const label = theme.fg("text", theme.bold("Type something."));
const desc = theme.fg("muted", "Enter a custom response");
const line = `${prefix} ${label} ${theme.fg("dim", "—")} ${desc}`;
lines.push(truncateToWidth(line, width, ""));
continue;
}
const option = this.options[i];
if (!option) continue;
const checkbox = this.checked.has(i) ? theme.fg("success", "[✓]") : theme.fg("dim", "[ ]");
const num = theme.fg("dim", `${i + 1}.`);
const title = isSelected
? theme.fg("accent", theme.bold(option.title))
: theme.fg("text", theme.bold(option.title));
const firstLine = `${prefix} ${num} ${checkbox} ${title}`;
lines.push(truncateToWidth(firstLine, width, ""));
if (option.description) {
const indent = " ";
const wrapWidth = Math.max(10, width - indent.length);
const wrapped = wrapTextWithAnsi(option.description, wrapWidth);
for (const w of wrapped) {
lines.push(truncateToWidth(indent + theme.fg("muted", w), width, ""));
}
}
}
if (startIndex > 0 || endIndex < count) {
lines.push(theme.fg("dim", truncateToWidth(` (${this.selectedIndex + 1}/${count})`, width, "")));
}
this.cachedWidth = width;
this.cachedLines = lines;
return lines;
}
}
class WrappedSingleSelectList implements Component {
private options: QuestionOption[];
private allowFreeform: boolean;
private allowComment: boolean;
private theme: Theme;
private keybindings: KeybindingsManager;
private selectedIndex = 0;
private searchQuery = "";
private commentEnabled = false;
private maxVisibleRows = 12;
private cachedWidth?: number;
private cachedLines?: string[];
public onCancel?: () => void;
public onSubmit?: (result: string) => void;
public onEnterFreeform?: () => void;
constructor(
options: QuestionOption[],
allowFreeform: boolean,
allowComment: boolean,
theme: Theme,
keybindings: KeybindingsManager,
) {
this.options = options;
this.allowFreeform = allowFreeform;
this.allowComment = allowComment;
this.theme = theme;
this.keybindings = keybindings;
}
public isCommentEnabled(): boolean {
return this.commentEnabled;
}
setMaxVisibleRows(rows: number): void {
const next = Math.max(1, Math.floor(rows));
if (next !== this.maxVisibleRows) {
this.maxVisibleRows = next;
this.invalidate();
}
}
invalidate(): void {
this.cachedWidth = undefined;
this.cachedLines = undefined;
}
private getFilteredOptions(): QuestionOption[] {
return fuzzyFilter(this.options, this.searchQuery, (option) => `${option.title} ${option.description ?? ""}`);
}
private getItemCount(filteredOptions: QuestionOption[]): number {
return filteredOptions.length + (this.allowComment ? 1 : 0) + (this.allowFreeform ? 1 : 0);
}
private isCommentToggleRow(index: number, filteredOptions: QuestionOption[]): boolean {
return this.allowComment && index === filteredOptions.length;
}
private isFreeformRow(index: number, filteredOptions: QuestionOption[]): boolean {
return this.allowFreeform && index === filteredOptions.length + (this.allowComment ? 1 : 0);
}
private toggleComment(): void {
if (!this.allowComment) return;
this.commentEnabled = !this.commentEnabled;
this.invalidate();
}
private setSearchQuery(query: string): void {
this.searchQuery = query;
this.selectedIndex = 0;
this.invalidate();
}
private popSearchCharacter(): void {
if (!this.searchQuery) return;
const characters = [...this.searchQuery];
characters.pop();
this.setSearchQuery(characters.join(""));
}
private getPrintableInput(data: string): string | null {
const kittyPrintable = decodeKittyPrintable(data);
if (kittyPrintable !== undefined) return kittyPrintable;
const characters = [...data];
if (characters.length !== 1) return null;
const [character] = characters;
if (!character) return null;
const code = character.charCodeAt(0);
if (code < 32 || code === 0x7f || (code >= 0x80 && code <= 0x9f)) {
return null;
}
return character;
}
private styleListLine(line: string, width: number, isSelected: boolean): string {
const trimmed = line.trim();
if (trimmed.startsWith("(")) {
return truncateToWidth(this.theme.fg("dim", line), width, "");
}
if (isSelected) {
return truncateToWidth(this.theme.fg("accent", this.theme.bold(line)), width, "");
}
if (line.startsWith(" ")) {
return truncateToWidth(this.theme.fg("muted", line), width, "");
}
if (line.startsWith("→")) {
return truncateToWidth(this.theme.fg("accent", this.theme.bold(line)), width, "");
}
return truncateToWidth(this.theme.fg("text", line), width, "");
}
private getSplitPaneWidths(width: number): { left: number; right: number } | null {
if (width < SINGLE_SELECT_SPLIT_PANE_MIN_WIDTH) return null;
const availableWidth = width - SINGLE_SELECT_SPLIT_PANE_SEPARATOR.length;
if (availableWidth < SINGLE_SELECT_SPLIT_PANE_LEFT_MIN_WIDTH + SINGLE_SELECT_SPLIT_PANE_RIGHT_MIN_WIDTH) {
return null;
}
const preferredLeftWidth = Math.floor(availableWidth * 0.42);
const left = Math.max(
SINGLE_SELECT_SPLIT_PANE_LEFT_MIN_WIDTH,
Math.min(preferredLeftWidth, availableWidth - SINGLE_SELECT_SPLIT_PANE_RIGHT_MIN_WIDTH),
);
const right = availableWidth - left;
if (right < SINGLE_SELECT_SPLIT_PANE_RIGHT_MIN_WIDTH) return null;
return { left, right };
}
private buildListLines(width: number, filteredOptions: QuestionOption[], hideDescriptions = false): string[] {
const lines: string[] = [];
const count = this.getItemCount(filteredOptions);
const searchValue = this.searchQuery ? this.theme.fg("text", this.searchQuery) : this.theme.fg("dim", "type to filter");
lines.push(truncateToWidth(`${this.theme.fg("accent", "Filter:")} ${searchValue}`, width, ""));
if (this.searchQuery && filteredOptions.length === 0) {
lines.push(truncateToWidth(this.theme.fg("warning", "No matching options"), width, ""));
}
if (count === 0) {
if (!this.searchQuery) {
lines.push(truncateToWidth(this.theme.fg("warning", "No options"), width, ""));
}
return lines.slice(0, this.maxVisibleRows);
}
const maxRows = Math.max(1, this.maxVisibleRows - lines.length);
const optionRows = renderSingleSelectRows({
options: filteredOptions,
selectedIndex: this.selectedIndex,
width,
allowFreeform: this.allowFreeform,
allowComment: this.allowComment,
commentEnabled: this.commentEnabled,
maxRows,
hideDescriptions,
});
const optionLines = optionRows.map((row) => this.styleListLine(row.line, width, row.selected));
lines.push(...optionLines);
return lines.slice(0, this.maxVisibleRows);
}
private buildPreviewLines(width: number, filteredOptions: QuestionOption[], maxLines: number): string[] {
if (maxLines <= 0) return [];
let mdTheme: MarkdownTheme | undefined;
try {
mdTheme = getMarkdownTheme();
} catch { }
let md = "";
if (this.isCommentToggleRow(this.selectedIndex, filteredOptions)) {
md += "## Additional context\n\n";
md += `Currently: **${this.commentEnabled ? "Enabled" : "Disabled"}**\n\n`;
md += "Turn this on when the selected option needs extra explanation before the tool submits.\n";
} else if (this.isFreeformRow(this.selectedIndex, filteredOptions)) {
md += "## Custom response\n\n";
md += "Open the editor to write **any** answer.\n\n";
md += "*Use this when none of the listed options fit.*\n";
if (this.searchQuery) {
md += `\n> Current filter: \`${this.searchQuery}\`\n`;
}
} else {
const selected = filteredOptions[this.selectedIndex];
if (!selected) {
md += "*No option selected*\n";
} else {
md += `## ${selected.title}\n\n`;
if (selected.description?.trim()) {
md += `${selected.description}\n`;
} else {
md += "*No additional details provided for this option.*\n";
}
md += `\n---\n\nPress \`Enter\` to select this option.\n`;
if (this.searchQuery) {
md += `\n> Filter: \`${this.searchQuery}\`\n`;
}
}
}
let lines: string[];
if (mdTheme) {
const mdComponent = new Markdown(md.trim(), 0, 0, mdTheme);
lines = mdComponent.render(width);
} else {
lines = [];
for (const line of wrapTextWithAnsi(md.trim(), Math.max(10, width))) {
lines.push(truncateToWidth(line, width, ""));
}
}
while (lines.length > 0 && lines[lines.length - 1]?.trim() === "") {
lines.pop();
}
if (lines.length <= maxLines) return lines;
if (maxLines === 1) return [truncateToWidth(this.theme.fg("dim", "…"), width, "")];
const visibleLines = lines.slice(0, maxLines - 1);
visibleLines.push(truncateToWidth(this.theme.fg("dim", "…"), width, ""));
return visibleLines;
}
handleInput(data: string): void {
if (this.searchQuery && matchesKey(data, Key.escape)) {
this.setSearchQuery("");
return;
}
if (this.keybindings.matches(data, "tui.select.cancel")) {
this.onCancel?.();
return;
}
if (this.allowComment && isCommentToggleKey(data)) {
this.toggleComment();
return;
}
const filteredOptions = this.getFilteredOptions();
const count = this.getItemCount(filteredOptions);
if ((this.keybindings.matches(data, "tui.select.up") || matchesKey(data, Key.shift("tab"))) && count > 0) {
this.selectedIndex = this.selectedIndex === 0 ? count - 1 : this.selectedIndex - 1;
this.invalidate();
return;
}
if ((this.keybindings.matches(data, "tui.select.down") || matchesKey(data, Key.tab)) && count > 0) {
this.selectedIndex = this.selectedIndex === count - 1 ? 0 : this.selectedIndex + 1;
this.invalidate();
return;
}
const numMatch = data.match(/^[1-9]$/);
if (numMatch && filteredOptions.length > 0) {
const idx = Number.parseInt(numMatch[0], 10) - 1;
if (idx >= 0 && idx < filteredOptions.length) {
this.selectedIndex = idx;
this.invalidate();
return;
}
}
if (matchesKey(data, Key.space) && count > 0 && this.isCommentToggleRow(this.selectedIndex, filteredOptions)) {
this.toggleComment();
return;
}
if (this.keybindings.matches(data, "tui.select.confirm") && count > 0) {
if (this.isCommentToggleRow(this.selectedIndex, filteredOptions)) {
this.toggleComment();
return;
}
if (this.isFreeformRow(this.selectedIndex, filteredOptions)) {
this.onEnterFreeform?.();
return;
}
const result = filteredOptions[this.selectedIndex]?.title;
if (result) this.onSubmit?.(result);
else this.onCancel?.();
return;
}
if (this.keybindings.matches(data, "tui.editor.deleteCharBackward") || matchesKey(data, Key.backspace)) {
this.popSearchCharacter();
return;
}
const printableInput = this.getPrintableInput(data);
if (printableInput) {
this.setSearchQuery(this.searchQuery + printableInput);
}
}
render(width: number): string[] {
if (this.cachedLines && this.cachedWidth === width) {
return this.cachedLines;
}
const filteredOptions = this.getFilteredOptions();
const count = this.getItemCount(filteredOptions);
this.selectedIndex = count > 0 ? Math.max(0, Math.min(this.selectedIndex, count - 1)) : 0;
const splitPane = this.getSplitPaneWidths(width);
let lines: string[];
if (!splitPane) {
lines = this.buildListLines(width, filteredOptions);
} else {
const listLines = this.buildListLines(splitPane.left, filteredOptions, true);
const previewLines = this.buildPreviewLines(splitPane.right, filteredOptions, this.maxVisibleRows);
const rowCount = Math.min(this.maxVisibleRows, Math.max(listLines.length, previewLines.length));
const separator = this.theme.fg("dim", SINGLE_SELECT_SPLIT_PANE_SEPARATOR);
lines = Array.from({ length: rowCount }, (_, index) => {
const left = truncateToWidth(listLines[index] ?? "", splitPane.left, "", true);
const right = truncateToWidth(previewLines[index] ?? "", splitPane.right, "");
return `${left}${separator}${right}`;
});
}
this.cachedWidth = width;
this.cachedLines = lines;
return lines;
}
}
/**
* Interactive ask UI. Uses a root Container for layout and swaps the center
* component between SelectList/MultiSelectList and an Editor (freeform mode).
*/
class AskComponent extends Container {
private question: string;
private context?: string;
private options: QuestionOption[];
private allowMultiple: boolean;
private allowFreeform: boolean;
private allowComment: boolean;
private tui: TUI;
private theme: Theme;
private keybindings: KeybindingsManager;
private onDone: (result: AskUIResult | null) => void;
private mode: AskMode = "select";
private pendingSelections: string[] = [];
private freeformDraft = "";
private commentDraft = "";
// Static layout components
private titleText: Text;
private questionText: Text;
private contextComponent?: Component;
private modeContainer: Container;
private helpText: Text;
// Mode components
private singleSelectList?: WrappedSingleSelectList;
private multiSelectList?: MultiSelectList;
private editor?: Editor;
// Focusable - propagate to Editor for IME cursor positioning
private _focused = false;
get focused(): boolean {
return this._focused;
}
set focused(value: boolean) {
this._focused = value;
if (this.editor && (this.mode === "freeform" || this.mode === "comment")) {
(this.editor as any).focused = value;
}
}
constructor(
question: string,
context: string | undefined,
options: QuestionOption[],
allowMultiple: boolean,
allowFreeform: boolean,
allowComment: boolean,
tui: TUI,
theme: Theme,
keybindings: KeybindingsManager,
onDone: (result: AskUIResult | null) => void,
) {
super();
this.question = question;
this.context = context;
this.options = options;
this.allowMultiple = allowMultiple;
this.allowFreeform = allowFreeform;
this.allowComment = allowComment;
this.tui = tui;
this.theme = theme;
this.keybindings = keybindings;
this.onDone = onDone;
// Layout skeleton
this.addChild(new BoxBorderTop(
(s: string) => theme.fg("accent", s),
"ask_user",
(s: string) => theme.fg("dim", theme.bold(s)),
));
this.addChild(new Spacer(1));
this.titleText = new Text("", 1, 0);
this.addChild(this.titleText);
this.addChild(new Spacer(1));
this.questionText = new Text("", 1, 0);
this.addChild(this.questionText);
if (this.context) {
this.addChild(new Spacer(1));
let mdTheme: MarkdownTheme | undefined;
try {
mdTheme = getMarkdownTheme();
} catch { }
if (mdTheme) {
this.contextComponent = new Markdown("", 1, 0, mdTheme);
} else {
this.contextComponent = new Text("", 1, 0);
}
this.addChild(this.contextComponent);
}
this.addChild(new Spacer(1));
this.modeContainer = new Container();
this.addChild(this.modeContainer);
this.addChild(new Spacer(1));
this.helpText = new Text("", 1, 0);
this.addChild(this.helpText);
this.addChild(new Spacer(1));
this.addChild(new BoxBorderBottom(
(s: string) => theme.fg("accent", s),
`v${ASK_USER_VERSION}`,
(s: string) => theme.fg("dim", s),
));
this.updateStaticText();
this.showSelectMode();
}
override invalidate(): void {
super.invalidate();
this.updateStaticText();
this.updateHelpText();
}
override render(width: number): string[] {
const innerWidth = Math.max(1, width - BOX_BORDER_OVERHEAD);
if (this.mode === "select" && !this.allowMultiple) {
const overlayMaxHeight = Math.max(12, Math.floor(this.tui.terminal.rows * ASK_OVERLAY_MAX_HEIGHT_RATIO));
const staticLines = this.countStaticLines(innerWidth);
const availableOptionRows = Math.max(4, overlayMaxHeight - staticLines);
this.ensureSingleSelectList().setMaxVisibleRows(availableOptionRows);
}
// Render children at the inner width (excluding side border characters)
const rawLines = super.render(innerWidth);
// First and last lines are the top/bottom box borders — pass through at full width.
// All inner lines get wrapped with side borders.
const borderColor = (s: string) => this.theme.fg("accent", s);
const titleColor = (s: string) => this.theme.fg("dim", this.theme.bold(s));
return rawLines.map((line, index) => {
if (index === 0 || index === rawLines.length - 1) {
// Box top/bottom borders already rendered at innerWidth — re-render at full width
if (index === 0) return new BoxBorderTop(borderColor, "ask_user", titleColor).render(width)[0];
return new BoxBorderBottom(borderColor, `v${ASK_USER_VERSION}`, (s: string) => this.theme.fg("dim", s)).render(width)[0];
}
const padded = truncateToWidth(line, innerWidth, "", true);
return `${borderColor(BOX_BORDER_LEFT)}${padded}${borderColor(BOX_BORDER_RIGHT)}`;
});
}
private countWrappedLines(text: string, width: number): number {
return Math.max(1, wrapTextWithAnsi(text, Math.max(10, width - 2)).length);
}
private countStaticLines(width: number): number {
const titleLines = 1;
const questionLines = this.countWrappedLines(this.question, width);
const contextLines = this.context ? 1 + this.countWrappedLines(this.context, width) : 0;
const helpLines = 1;
const borderLines = 2;
const spacerLines = this.context ? 6 : 5;
return borderLines + spacerLines + titleLines + questionLines + contextLines + helpLines;
}
private updateStaticText(): void {
const theme = this.theme;
const title = this.mode === "comment" ? "Optional comment" : "Question";
this.titleText.setText(theme.fg("accent", theme.bold(title)));
this.questionText.setText(theme.fg("text", theme.bold(this.question)));
if (this.contextComponent && this.context) {
if (this.contextComponent instanceof Markdown) {
(this.contextComponent as Markdown).setText(
`**Context:**\n${this.context}`,
);
} else {
(this.contextComponent as Text).setText(
`${theme.fg("accent", theme.bold("Context:"))}\n${theme.fg("dim", this.context)}`,
);
}
}
}
private updateHelpText(): void {
const theme = this.theme;
if (this.mode === "freeform" || this.mode === "comment") {
const alternateCancelKeys = this.keybindings
.getKeys("tui.select.cancel")
.filter((key) => key !== "escape" && key !== "esc");
const hints = [
keybindingHint(theme, this.keybindings, "tui.input.submit", this.mode === "comment" ? "submit/skip" : "submit"),
keybindingHint(theme, this.keybindings, "tui.input.newLine", "newline"),