@luxass/pi-questions 0.1.2 → 0.1.3

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/src/dialog.ts CHANGED
@@ -1,13 +1,17 @@
1
1
  import { getMarkdownTheme, type Theme } from "@earendil-works/pi-coding-agent";
2
2
  import {
3
+ Box,
4
+ Container,
3
5
  CURSOR_MARKER,
4
6
  Editor,
7
+ HStack,
5
8
  isKeyRelease,
6
9
  isKeyRepeat,
7
10
  Markdown,
8
11
  matchesKey,
9
- ScrollView,
10
- stripTerminalSequences,
12
+ MouseRegion,
13
+ Spacer,
14
+ Text,
11
15
  truncateToWidth,
12
16
  visibleWidth,
13
17
  wrapTextWithAnsi,
@@ -23,10 +27,11 @@ import {
23
27
  answerText,
24
28
  cancelledResult,
25
29
  collectAnswers,
26
- type AnswerDraft,
30
+ type Question,
27
31
  type QuestionResult,
28
32
  type Questions,
29
33
  } from "./questions.ts";
34
+ import { Viewport } from "./viewport.ts";
30
35
 
31
36
  interface DialogOptions {
32
37
  params: Questions;
@@ -36,8 +41,17 @@ interface DialogOptions {
36
41
  done: (result: QuestionResult) => void;
37
42
  }
38
43
 
39
- type EditMode = "custom" | "notes";
40
- type Mode = EditMode | "preview" | "question" | undefined;
44
+ type Mode = "custom" | "notes" | "preview" | "question" | undefined;
45
+
46
+ /** One question's tab. Its editors hold the custom answer and the note. */
47
+ interface Tab {
48
+ question: Question;
49
+ selected: Set<number>;
50
+ /** Options, then `Type something.`, then Next or Submit. */
51
+ row: number;
52
+ custom: Editor;
53
+ notes: Editor;
54
+ }
41
55
 
42
56
  interface Keys {
43
57
  cancel: boolean;
@@ -47,17 +61,75 @@ interface Keys {
47
61
  newLine: boolean;
48
62
  }
49
63
 
64
+ interface ButtonOptions {
65
+ theme: Theme;
66
+ label: string;
67
+ description?: string;
68
+ active: boolean;
69
+ onActivate: () => void;
70
+ }
71
+
72
+ /** The width of tab cells separated by one column. */
73
+ const span = (sizes: number[]) => sizes.reduce((sum, size) => sum + size + 1, -1);
74
+
75
+ /** A whole-row button. Keyboard selection remains owned by the containing dialog. */
76
+ class Button extends MouseRegion {
77
+ constructor({ theme, label, description, active, onActivate }: ButtonOptions) {
78
+ super(
79
+ {
80
+ render(width) {
81
+ const content = new Box(
82
+ 0,
83
+ 0,
84
+ active ? (text) => theme.bg("selectedBg", text) : undefined,
85
+ );
86
+ const title = `${active ? "›" : " "} ${label}`;
87
+ const styled = theme.fg(active ? "accent" : "text", title);
88
+ content.addChild(new Text(active ? theme.bold(styled) : styled, 0, 0));
89
+ if (description) {
90
+ const indent = Math.min(7, Math.max(0, width - 1));
91
+ content.addChild({
92
+ render: () =>
93
+ wrapTextWithAnsi(theme.fg("muted", description), width - indent).map(
94
+ (line) => " ".repeat(indent) + line,
95
+ ),
96
+ invalidate() {},
97
+ });
98
+ }
99
+ return content.render(width);
100
+ },
101
+ invalidate() {},
102
+ },
103
+ (event) => {
104
+ if (
105
+ event.button !== "left" ||
106
+ event.shift ||
107
+ event.alt ||
108
+ event.ctrl ||
109
+ (event.type !== "press" && event.type !== "click") ||
110
+ event.x < 0 ||
111
+ event.x >= event.width ||
112
+ event.y < 0 ||
113
+ event.y >= event.height
114
+ )
115
+ return undefined;
116
+ // Activating on press can reflow the choices before the click arrives.
117
+ if (event.type === "click") onActivate();
118
+ return { handled: true, focus: true };
119
+ },
120
+ );
121
+ }
122
+ }
123
+
50
124
  export class QuestionDialog implements Component, Focusable {
51
125
  private readonly options: DialogOptions;
52
- private readonly questions: Questions["questions"];
53
- private readonly drafts: AnswerDraft[];
54
- private readonly rows: number[];
55
- private readonly editors = new Map<string, Editor>();
126
+ private readonly tabs: Tab[];
127
+ private readonly globalNote: Editor;
56
128
  private readonly markdown = new Map<string, Markdown>();
57
- private readonly scroll: ScrollView;
129
+ private readonly content = new Container();
130
+ private readonly scroll: Viewport;
58
131
  private tab = 0;
59
132
  private mode: Mode;
60
- private globalNote = "";
61
133
  private reviewRow = 0;
62
134
  private focus = false;
63
135
  private closed = false;
@@ -68,23 +140,28 @@ export class QuestionDialog implements Component, Focusable {
68
140
  private warning = "";
69
141
  private headerTargets: { tab: number; start: number; end: number }[] = [];
70
142
  private mouseWidth = 0;
143
+ private bodyTop = 0;
144
+ private bodyHeight = 0;
71
145
 
72
146
  constructor(options: DialogOptions) {
73
147
  this.options = options;
74
- this.questions = options.params.questions;
75
- this.drafts = this.questions.map(() => ({
76
- selected: new Set<number>(),
77
- custom: "",
78
- notes: "",
79
- }));
80
- this.rows = this.questions.map(() => 0);
81
- this.scroll = new ScrollView(
82
- {
83
- render: (width) => this.body(width),
84
- invalidate: () => this.markdown.clear(),
85
- },
86
- { scrollbar: "hidden" },
87
- );
148
+ this.tabs = options.params.questions.map((question) => {
149
+ const tab: Tab = {
150
+ question,
151
+ selected: new Set(),
152
+ row: 0,
153
+ custom: this.newEditor(),
154
+ notes: this.newEditor(),
155
+ };
156
+ // Single-choice custom text replaces the chosen option.
157
+ if (!question.multiSelect)
158
+ tab.custom.onChange = (text) => {
159
+ if (text.trim()) tab.selected.clear();
160
+ };
161
+ return tab;
162
+ });
163
+ this.globalNote = this.newEditor();
164
+ this.scroll = new Viewport(this.content, () => options.tui.requestRender());
88
165
  }
89
166
 
90
167
  get focused(): boolean {
@@ -95,30 +172,37 @@ export class QuestionDialog implements Component, Focusable {
95
172
  this.syncFocus();
96
173
  }
97
174
 
98
- /** The Review tab follows the question tabs and only exists with several questions. */
175
+ /** Undefined on the Review tab, which follows the question tabs when there are several. */
176
+ private get current(): Tab | undefined {
177
+ return this.tabs[this.tab];
178
+ }
179
+
99
180
  private get isReview(): boolean {
100
- return this.tab === this.drafts.length;
181
+ return this.tab === this.tabs.length;
101
182
  }
102
183
 
103
184
  /** Focusing the `Type something.` row, which follows the options, opens its editor. */
104
- private modeForRow(tab: number): Mode {
105
- const question = this.questions[tab];
106
- return question && this.rows[tab] === question.options.length ? "custom" : undefined;
185
+ private modeForRow(): Mode {
186
+ const tab = this.current;
187
+ return tab && tab.row === tab.question.options.length ? "custom" : undefined;
188
+ }
189
+
190
+ private activeEditor(): Editor | undefined {
191
+ if (this.mode === "notes") return this.current?.notes ?? this.globalNote;
192
+ if (this.mode === "custom") return this.current?.custom;
193
+ return undefined;
107
194
  }
108
195
 
109
196
  private syncFocus(): void {
110
- for (const editor of this.editors.values()) editor.focused = false;
111
- if (!this.collapsed && (this.mode === "custom" || this.mode === "notes"))
112
- this.editor(this.mode).focused = this.focus;
197
+ this.globalNote.focused = false;
198
+ for (const tab of this.tabs) tab.custom.focused = tab.notes.focused = false;
199
+ const editor = this.activeEditor();
200
+ if (editor && !this.collapsed) editor.focused = this.focus;
113
201
  }
114
202
 
115
- private editor(mode: EditMode): Editor {
116
- const key = `${this.tab}:${mode}`;
117
- const existing = this.editors.get(key);
118
- if (existing) return existing;
203
+ private newEditor(): Editor {
119
204
  const { tui, theme } = this.options;
120
- const tab = this.tab;
121
- const editor = new Editor(
205
+ return new Editor(
122
206
  tui,
123
207
  {
124
208
  borderColor: (text) => theme.fg("accent", text),
@@ -132,45 +216,24 @@ export class QuestionDialog implements Component, Focusable {
132
216
  },
133
217
  { paddingX: 0 },
134
218
  );
135
- editor.onChange = () => {
136
- // Multi-select custom text counts while typing; single-choice text counts once committed.
137
- if (mode === "custom" && this.questions[tab]?.multiSelect)
138
- this.drafts[tab]!.custom = editor.getExpandedText().trim();
139
- };
140
- editor.onSubmit = (text) => {
141
- const value = text.trim();
142
- const question = this.questions[tab];
143
- const draft = this.drafts[tab];
144
- // An empty single-choice custom answer is not a choice.
145
- if (mode === "custom" && !value && !question?.multiSelect) return;
146
- // Pi's Editor clears itself on submit. Keep saved text editable on return.
147
- editor.setText(value);
148
- if (mode === "notes") {
149
- if (draft) draft.notes = value;
150
- else this.globalNote = value;
151
- } else if (draft) {
152
- draft.custom = value;
153
- if (value && !question?.multiSelect) draft.selected.clear();
154
- }
155
- // Leaving a note returns to the custom editor if that row is focused.
156
- this.mode = mode === "notes" ? this.modeForRow(tab) : undefined;
157
- if (mode === "custom") {
158
- // If we are in multi select mode, we should not advance.
159
- if (!question?.multiSelect) this.advance();
160
- }
219
+ }
161
220
 
162
- this.syncFocus();
163
- this.followSelection = true;
164
- tui.requestRender();
165
- };
166
- this.editors.set(key, editor);
167
- return editor;
221
+ private collect(): QuestionResult {
222
+ return collectAnswers(
223
+ this.options.params,
224
+ this.tabs.map((tab) => ({
225
+ selected: tab.selected,
226
+ custom: tab.custom.getExpandedText(),
227
+ notes: tab.notes.getExpandedText(),
228
+ })),
229
+ this.globalNote.getExpandedText(),
230
+ );
168
231
  }
169
232
 
170
233
  private switchTab(tab: number): void {
171
- const count = this.drafts.length + (this.drafts.length > 1 ? 1 : 0);
234
+ const count = this.tabs.length + (this.tabs.length > 1 ? 1 : 0);
172
235
  this.tab = (tab + count) % count;
173
- this.mode = this.modeForRow(this.tab);
236
+ this.mode = this.modeForRow();
174
237
  this.warning = "";
175
238
  this.scroll.scrollToStart();
176
239
  this.followSelection = true;
@@ -179,11 +242,11 @@ export class QuestionDialog implements Component, Focusable {
179
242
 
180
243
  /** Moves to the next tab, or submits directly when there is only one question. */
181
244
  private advance(): void {
182
- if (this.drafts.length > 1) {
245
+ if (this.tabs.length > 1) {
183
246
  this.switchTab(this.tab + 1);
184
247
  return;
185
248
  }
186
- const result = collectAnswers(this.options.params, this.drafts, this.globalNote);
249
+ const result = this.collect();
187
250
  if (result.answers.length) this.finish(result);
188
251
  else this.warning = "Choose an option, write an answer, or add a note.";
189
252
  }
@@ -191,12 +254,10 @@ export class QuestionDialog implements Component, Focusable {
191
254
  private moveRow(delta: number): void {
192
255
  if (this.isReview) this.reviewRow = (this.reviewRow + delta + 2) % 2;
193
256
  else {
194
- const question = this.questions[this.tab]!;
195
- // Options, `Type something.`, and a Next or Submit row when needed.
196
- const count =
197
- question.options.length + (question.multiSelect || this.questions.length === 1 ? 2 : 1);
198
- this.rows[this.tab] = (this.rows[this.tab]! + delta + count) % count;
199
- this.mode = this.modeForRow(this.tab);
257
+ const tab = this.current!;
258
+ const count = tab.question.options.length + 2;
259
+ tab.row = (tab.row + delta + count) % count;
260
+ this.mode = this.modeForRow();
200
261
  this.syncFocus();
201
262
  }
202
263
  this.followSelection = true;
@@ -218,7 +279,7 @@ export class QuestionDialog implements Component, Focusable {
218
279
  this.finish(cancelledResult());
219
280
  return;
220
281
  }
221
- const result = collectAnswers(this.options.params, this.drafts, this.globalNote);
282
+ const result = this.collect();
222
283
  if (!result.answers.length && !result.globalNote) {
223
284
  this.warning = "Provide an answer or a note before submitting.";
224
285
  this.followSelection = true;
@@ -227,9 +288,8 @@ export class QuestionDialog implements Component, Focusable {
227
288
  this.finish(result);
228
289
  return;
229
290
  }
230
- const question = this.questions[this.tab]!;
231
- const row = this.rows[this.tab]!;
232
- const draft = this.drafts[this.tab]!;
291
+ const tab = this.current!;
292
+ const { question, row } = tab;
233
293
  if (row === question.options.length) {
234
294
  this.mode = "custom";
235
295
  this.scroll.scrollToStart();
@@ -238,19 +298,47 @@ export class QuestionDialog implements Component, Focusable {
238
298
  // The Next or Submit row.
239
299
  this.advance();
240
300
  } else if (question.multiSelect) {
241
- if (draft.selected.has(row)) draft.selected.delete(row);
242
- else draft.selected.add(row);
301
+ if (tab.selected.has(row)) tab.selected.delete(row);
302
+ else tab.selected.add(row);
243
303
  } else {
244
- draft.selected.clear();
245
- draft.selected.add(row);
246
- draft.custom = "";
304
+ tab.selected.clear();
305
+ tab.selected.add(row);
306
+ tab.custom.setText("");
247
307
  this.advance();
248
308
  }
249
309
  this.followSelection = true;
250
310
  }
251
311
 
312
+ /** Enter saves the custom answer. A single-choice answer also moves on. */
313
+ private submitCustom(): void {
314
+ const { question, custom } = this.current!;
315
+ // An empty single-choice custom answer is not a choice.
316
+ if (!question.multiSelect && !custom.getExpandedText().trim()) return;
317
+ this.mode = undefined;
318
+ if (!question.multiSelect) this.advance();
319
+ this.syncFocus();
320
+ this.followSelection = true;
321
+ }
322
+
323
+ /** Enter and Escape both keep the note. */
324
+ private closeNote(): void {
325
+ // Leaving a note returns to the custom editor if that row is focused.
326
+ this.mode = this.modeForRow();
327
+ this.syncFocus();
328
+ this.followSelection = true;
329
+ }
330
+
331
+ private activateRow(row: number): void {
332
+ if (this.isReview) this.reviewRow = row;
333
+ else this.current!.row = row;
334
+ this.mode = undefined;
335
+ this.choose();
336
+ this.syncFocus();
337
+ }
338
+
252
339
  private preview(): string | undefined {
253
- return this.questions[this.tab]?.options[this.rows[this.tab] ?? 0]?.preview;
340
+ const tab = this.current;
341
+ return tab?.question.options[tab.row]?.preview;
254
342
  }
255
343
 
256
344
  private wrap(
@@ -258,111 +346,127 @@ export class QuestionDialog implements Component, Focusable {
258
346
  width: number,
259
347
  color: "text" | "muted" | "accent" | "warning" = "text",
260
348
  ): string[] {
261
- return wrapTextWithAnsi(this.options.theme.fg(color, stripTerminalSequences(text)), width);
349
+ return wrapTextWithAnsi(this.options.theme.fg(color, text), width);
262
350
  }
263
351
 
264
- private previewLines(text: string, width: number): string[] {
352
+ private previewComponent(text: string): Markdown {
265
353
  let component = this.markdown.get(text);
266
354
  if (!component) {
267
- component = new Markdown(stripTerminalSequences(text), 0, 0, getMarkdownTheme());
355
+ component = new Markdown(text, 0, 0, getMarkdownTheme());
268
356
  this.markdown.set(text, component);
269
357
  }
270
- return component.render(width);
358
+ return component;
271
359
  }
272
360
 
273
361
  private get answeredCount(): number {
274
- return this.drafts.filter((draft) => draft.selected.size > 0 || draft.custom.trim()).length;
362
+ return this.tabs.filter((tab) => tab.selected.size > 0 || tab.custom.getExpandedText().trim())
363
+ .length;
275
364
  }
276
365
 
277
- /** Keep selection backgrounds inside the content pane, including wrapped lines. */
278
- private highlight(text: string, width: number, active: boolean): string {
279
- if (!active) return text;
280
- const fitted = truncateToWidth(text, width, "");
281
- return this.options.theme.bg(
282
- "selectedBg",
283
- fitted + " ".repeat(Math.max(0, width - visibleWidth(fitted))),
284
- );
285
- }
286
-
287
- private questionBody(width: number): string[] {
288
- const question = this.questions[this.tab]!;
289
- const draft = this.drafts[this.tab]!;
366
+ private questionBody(width: number): Component {
367
+ const { theme } = this.options;
368
+ const tab = this.current!;
369
+ const { question } = tab;
290
370
  const preview = this.preview();
291
371
  const sideBySide = Boolean(preview && width >= 96);
292
372
  const leftWidth = sideBySide ? Math.floor(width * 0.45) : width;
293
- const lines: string[] = [];
294
- const current = this.rows[this.tab]!;
373
+ const choices = new Container();
295
374
  const add = (index: number, label: string, description?: string) => {
296
- const active = index === current;
297
- if (active) this.selectedLine = lines.length;
298
- const title = this.wrap(
299
- `${active ? "›" : " "} ${label}`,
300
- leftWidth,
301
- active ? "accent" : "text",
375
+ const active = index === tab.row;
376
+ // This measurement is only for keyboard scrolling. Containers route mouse events.
377
+ if (active) this.selectedLine = choices.render(leftWidth).length;
378
+ choices.addChild(
379
+ new Button({
380
+ theme,
381
+ label,
382
+ description,
383
+ active,
384
+ onActivate: () => this.activateRow(index),
385
+ }),
302
386
  );
303
- lines.push(
304
- ...title.map((line) =>
305
- this.highlight(active ? this.options.theme.bold(line) : line, leftWidth, active),
306
- ),
307
- );
308
- if (description) {
309
- const indent = Math.min(7, Math.max(0, leftWidth - 1));
310
- lines.push(
311
- ...this.wrap(description, leftWidth - indent, "muted").map((line) =>
312
- this.highlight(" ".repeat(indent) + line, leftWidth, active),
313
- ),
314
- );
315
- }
316
- lines.push("");
387
+ choices.addChild(new Spacer(1));
317
388
  };
318
389
  question.options.forEach((option, index) => {
319
- const checked = draft.selected.has(index);
390
+ const checked = tab.selected.has(index);
320
391
  const marker = question.multiSelect ? (checked ? "■" : "□") : checked ? "●" : "○";
321
392
  add(index, `${marker} ${index + 1} ${option.label}`, option.description);
322
393
  });
323
- // Uncommitted editor text wins over the committed custom answer.
324
- const customText =
325
- this.editors.get(`${this.tab}:custom`)?.getExpandedText().trim() || draft.custom;
394
+ const customText = tab.custom.getExpandedText().trim();
326
395
  add(
327
396
  question.options.length,
328
397
  `${question.multiSelect ? (customText ? "■ " : "□ ") : "✎ "}Type something.`,
329
398
  this.mode === "custom" ? undefined : customText || "Write your own answer.",
330
399
  );
331
- if (this.mode === "custom") lines.push(...this.editor("custom").render(width), "");
332
- if (this.questions.length === 1 && !question.multiSelect)
400
+ if (this.mode === "custom") {
401
+ choices.addChild(tab.custom);
402
+ choices.addChild(new Spacer(1));
403
+ }
404
+ if (this.tabs.length === 1)
333
405
  add(
334
406
  question.options.length + 1,
335
407
  "Submit",
336
408
  "Submit an answer or a note. Notes alone leave this question undecided.",
337
409
  );
338
- else if (question.multiSelect)
339
- add(question.options.length + 1, "Next", "Keep these choices and move to the next tab.");
340
- if (draft.notes) lines.push(...this.wrap(`✎ Note: ${draft.notes}`, leftWidth, "muted"));
341
- if (this.warning) lines.push(...this.wrap(`! ${this.warning}`, leftWidth, "warning"));
342
- if (!preview) return lines;
343
- const previewWidth = sideBySide ? width - leftWidth - 3 : width;
344
- const rendered = this.previewLines(preview, previewWidth);
345
- const pane = [
346
- this.options.theme.fg("accent", "Preview"),
347
- ...this.wrap(question.options[current]!.label, previewWidth, "muted"),
348
- this.options.theme.fg("borderMuted", "─".repeat(previewWidth)),
349
- ...rendered.slice(0, 10),
350
- ];
351
- if (rendered.length > 10) pane.push(this.options.theme.fg("dim", "… press p to read more"));
352
- if (!sideBySide) return [...lines, "", ...pane];
353
- return Array.from({ length: Math.max(lines.length, pane.length) }, (_unused, index) => {
354
- const left = truncateToWidth(lines[index] ?? "", leftWidth, "");
355
- return (
356
- left +
357
- " ".repeat(Math.max(0, leftWidth - visibleWidth(left))) +
358
- this.options.theme.fg("borderAccent", " │ ") +
359
- (pane[index] ?? "")
410
+ else add(question.options.length + 1, "Next", "Keep this answer and move to the next tab.");
411
+ const notes = tab.notes.getExpandedText().trim();
412
+ if (notes)
413
+ choices.addChild(
414
+ new Text(this.wrap(`✎ Note: ${notes}`, leftWidth, "muted").join("\n"), 0, 0),
360
415
  );
361
- });
416
+ if (this.warning)
417
+ choices.addChild(
418
+ new Text(this.wrap(`! ${this.warning}`, leftWidth, "warning").join("\n"), 0, 0),
419
+ );
420
+ if (!preview) return choices;
421
+ const pane: Component = {
422
+ render: (paneWidth) => {
423
+ const rendered = this.previewComponent(preview).render(paneWidth);
424
+ const lines = [
425
+ theme.fg("accent", "Preview"),
426
+ ...this.wrap(question.options[tab.row]!.label, paneWidth, "muted"),
427
+ theme.fg("borderMuted", "─".repeat(paneWidth)),
428
+ ...rendered.slice(0, 10),
429
+ ];
430
+ if (rendered.length > 10) lines.push(theme.fg("dim", "… press p to read more"));
431
+ return lines;
432
+ },
433
+ invalidate() {},
434
+ };
435
+ if (!sideBySide) {
436
+ const layout = new Container();
437
+ layout.addChild(choices);
438
+ layout.addChild(new Spacer(1));
439
+ layout.addChild(pane);
440
+ return layout;
441
+ }
442
+ const previewWidth = width - leftWidth - 3;
443
+ const divider: Component = {
444
+ render: () =>
445
+ Array.from(
446
+ { length: Math.max(choices.render(leftWidth).length, pane.render(previewWidth).length) },
447
+ () => theme.fg("borderAccent", " │ "),
448
+ ),
449
+ invalidate() {},
450
+ };
451
+ const layout = new HStack([
452
+ { component: choices, basis: leftWidth, shrink: 0 },
453
+ { component: divider, basis: 3, shrink: 0 },
454
+ { component: pane, basis: previewWidth, shrink: 0 },
455
+ ]);
456
+ return {
457
+ render: (available) => layout.render(available),
458
+ // HStack's standalone handler uses vertical Container routing. Only the
459
+ // choices pane is interactive here, so forward it with its actual width.
460
+ handleMouse: (event) =>
461
+ event.x >= 0 && event.x < leftWidth
462
+ ? choices.handleMouse({ ...event, width: leftWidth })
463
+ : undefined,
464
+ invalidate: () => layout.invalidate(),
465
+ };
362
466
  }
363
467
 
364
- private reviewBody(width: number): string[] {
365
- const result = collectAnswers(this.options.params, this.drafts, this.globalNote);
468
+ private reviewBody(width: number): Component {
469
+ const result = this.collect();
366
470
  const lines = [
367
471
  this.options.theme.bold(this.options.theme.fg("accent", "Review your answers")),
368
472
  ...this.wrap(
@@ -372,7 +476,7 @@ export class QuestionDialog implements Component, Focusable {
372
476
  ),
373
477
  "",
374
478
  ];
375
- this.questions.forEach((question, index) => {
479
+ this.tabs.forEach(({ question }, index) => {
376
480
  const answer = result.answers.find((candidate) => candidate.questionIndex === index);
377
481
  const answered = !result.unanswered?.includes(index);
378
482
  lines.push(
@@ -387,78 +491,69 @@ export class QuestionDialog implements Component, Focusable {
387
491
  if (answer?.notes) lines.push(...this.wrap(` ✎ ${answer.notes}`, width, "muted"));
388
492
  lines.push("");
389
493
  });
390
- if (this.globalNote)
391
- lines.push("", ...this.wrap(`Global note: ${this.globalNote}`, width, "muted"));
494
+ if (result.globalNote)
495
+ lines.push("", ...this.wrap(`Global note: ${result.globalNote}`, width, "muted"));
392
496
  if (result.unanswered?.length)
393
497
  lines.push(
394
498
  "",
395
499
  ...this.wrap(
396
- `Unanswered: ${result.unanswered.map((index) => this.questions[index]!.header).join(", ")}. Submitting leaves these undecided.`,
500
+ `Unanswered: ${result.unanswered.map((index) => this.tabs[index]!.question.header).join(", ")}. Submitting leaves these undecided.`,
397
501
  width,
398
502
  "warning",
399
503
  ),
400
504
  );
401
505
  if (this.warning) lines.push("", ...this.wrap(this.warning, width, "warning"));
402
506
  lines.push("");
507
+ const content = new Container();
508
+ content.addChild(new Text(lines.join("\n"), 0, 0));
403
509
  ["Submit answers", "Cancel questionnaire"].forEach((label, index) => {
404
510
  const active = index === this.reviewRow;
405
- if (active) this.selectedLine = lines.length;
406
- lines.push(
407
- ...this.wrap(`${active ? "›" : " "} ${label}`, width, active ? "accent" : "muted").map(
408
- (line) => this.highlight(line, width, active),
409
- ),
511
+ if (active) this.selectedLine = content.render(width).length;
512
+ content.addChild(
513
+ new Button({
514
+ theme: this.options.theme,
515
+ label,
516
+ active,
517
+ onActivate: () => this.activateRow(index),
518
+ }),
410
519
  );
411
520
  });
412
- return lines;
521
+ return content;
413
522
  }
414
523
 
415
- private body(width: number): string[] {
524
+ private body(width: number): Component {
416
525
  if (this.mode === "notes") {
417
526
  const title = this.isReview ? "Global note" : "Question note";
418
- return [this.options.theme.fg("accent", title), ...this.editor("notes").render(width)];
527
+ const content = new Container();
528
+ content.addChild(new Text(this.options.theme.fg("accent", title), 0, 0));
529
+ content.addChild(this.activeEditor()!);
530
+ return content;
419
531
  }
420
- if (this.mode === "preview") return this.previewLines(this.preview() ?? "", width);
532
+ if (this.mode === "preview") return this.previewComponent(this.preview() ?? "");
421
533
  if (this.mode === "question")
422
- return this.wrap(this.questions[this.tab]!.question, width, "accent");
534
+ return new Text(this.wrap(this.current!.question.question, width, "accent").join("\n"), 0, 0);
423
535
  this.selectedLine = 0;
424
536
  return this.isReview ? this.reviewBody(width) : this.questionBody(width);
425
537
  }
426
538
 
427
539
  private renderNavigation(width: number): string[] {
428
540
  const { theme } = this.options;
429
- const titles = this.questions.map((question) => stripTerminalSequences(question.header));
541
+ const titles = this.tabs.map((tab) => tab.question.header);
430
542
  if (titles.length === 1) return [theme.fg("muted", truncateToWidth(titles[0]!, width, ""))];
431
543
  titles.push("Review");
432
- const titleWidths = titles.map(visibleWidth);
433
- const titleWidth = titleWidths.reduce((sum, size) => sum + size, 0);
434
- const gap =
435
- width >= titleWidth + 2 * (titles.length - 1) ? 2 : width >= titles.length * 2 - 1 ? 1 : 0;
436
- const available = width - gap * (titles.length - 1);
437
- const padding = titleWidth + titles.length * 2 <= available ? 2 : 0;
438
- const sizes = titleWidths.map((size) => size + padding);
439
- let used = sizes.reduce((sum, size) => sum + size, 0);
440
- // Short tabs keep their space; only the widest titles shrink when necessary.
441
- while (used > available) {
442
- const widest = sizes.indexOf(Math.max(...sizes));
443
- sizes[widest]!--;
444
- used--;
544
+ // Tabs keep their natural width when they fit. Otherwise they share the width equally.
545
+ let sizes = titles.map((title) => visibleWidth(title) + 2);
546
+ if (span(sizes) > width) {
547
+ const size = Math.max(1, Math.floor((width - titles.length + 1) / titles.length));
548
+ sizes = titles.map(() => size);
445
549
  }
446
- const spare = available - used;
447
- const extra = Math.floor(spare / titles.length);
448
- const remainder = spare % titles.length;
449
550
  // Mouse coordinates include the frame's two-column left inset.
450
551
  let column = 2;
451
552
  const cells = titles.map((title, index) => {
452
- const size = sizes[index]! + extra + (index < remainder ? 1 : 0);
553
+ const size = sizes[index]!;
453
554
  this.headerTargets.push({ tab: index, start: column, end: column + size });
454
- column += size + gap;
455
- const compact = index === this.questions.length ? "R" : String(index + 1);
456
- const label =
457
- titleWidths[index]! <= size
458
- ? title
459
- : size < 4
460
- ? compact
461
- : truncateToWidth(title, size, "…");
555
+ column += size + 1;
556
+ const label = truncateToWidth(title, size, "…");
462
557
  const padding = size - visibleWidth(label);
463
558
  const centered =
464
559
  " ".repeat(Math.floor(padding / 2)) + label + " ".repeat(Math.ceil(padding / 2));
@@ -469,8 +564,9 @@ export class QuestionDialog implements Component, Focusable {
469
564
  };
470
565
  });
471
566
  return [
472
- cells.map((cell) => cell.title).join(" ".repeat(gap)),
473
- cells.map((cell) => cell.rail).join(theme.fg("borderMuted", "─".repeat(gap))),
567
+ cells.map((cell) => cell.title).join(" "),
568
+ cells.map((cell) => cell.rail).join(theme.fg("borderMuted", "─")) +
569
+ theme.fg("borderMuted", "─".repeat(Math.max(0, width - span(sizes)))),
474
570
  ];
475
571
  }
476
572
 
@@ -492,18 +588,18 @@ export class QuestionDialog implements Component, Focusable {
492
588
  ["Ctrl+]", "collapse"],
493
589
  ];
494
590
  else {
495
- const question = this.questions[this.tab];
496
- const onAction = question && this.rows[this.tab]! > question.options.length;
591
+ const tab = this.current;
497
592
  let confirm = "choose";
498
593
  if (this.isReview) confirm = this.reviewRow === 0 ? "submit" : "cancel";
499
- else if (onAction) confirm = this.questions.length === 1 ? "submit" : "next";
500
- else if (question?.multiSelect) confirm = "toggle";
594
+ else if (tab && tab.row > tab.question.options.length)
595
+ confirm = this.tabs.length === 1 ? "submit" : "next";
596
+ else if (tab?.question.multiSelect) confirm = "toggle";
501
597
  hints = [
502
598
  ["Enter", confirm],
503
599
  ["↑↓", "move"],
504
600
  ["Esc", "cancel"],
505
601
  ];
506
- if (this.drafts.length > 1) hints.push(["Tab", "next"]);
602
+ if (this.tabs.length > 1) hints.push(["Tab", "next"]);
507
603
  if (this.isReview) hints.push(["Home/End", "scroll"]);
508
604
  if (this.preview()) hints.push(["p", "preview"]);
509
605
  hints.push(["n", "note"], ["Ctrl+]", "collapse"]);
@@ -537,12 +633,13 @@ export class QuestionDialog implements Component, Focusable {
537
633
  const { theme, tui } = this.options;
538
634
  this.headerTargets = [];
539
635
  this.mouseWidth = width;
636
+ this.bodyHeight = 0;
540
637
  if (this.collapsed)
541
638
  return [
542
639
  theme.fg(
543
640
  "dim",
544
641
  truncateToWidth(
545
- `Questions · ${this.answeredCount}/${this.questions.length} answered · Ctrl+] expand · Esc cancel`,
642
+ `Questions · ${this.answeredCount}/${this.tabs.length} answered · Ctrl+] expand · Esc cancel`,
546
643
  Math.max(0, width),
547
644
  "",
548
645
  ),
@@ -559,9 +656,7 @@ export class QuestionDialog implements Component, Focusable {
559
656
  const reading = this.mode === "preview" || this.mode === "question";
560
657
  let heading =
561
658
  !this.isReview && !reading
562
- ? this.wrap(this.questions[this.tab]!.question, inner, "text").map((line) =>
563
- theme.bold(line),
564
- )
659
+ ? this.wrap(this.current!.question.question, inner, "text").map((line) => theme.bold(line))
565
660
  : [];
566
661
  const headingLimit = Math.min(3, height - navigation.length - 5);
567
662
  if (heading.length > headingLimit)
@@ -570,25 +665,25 @@ export class QuestionDialog implements Component, Focusable {
570
665
  theme.fg("muted", truncateToWidth("… q to read full question", inner, "")),
571
666
  ];
572
667
  if (heading.length) heading.push("");
668
+ // Keep the component tree intact so containers can route clicks to buttons.
669
+ this.content.clear();
670
+ this.content.addChild(this.body(inner));
573
671
  // Borders and help take three rows. Short content leaves more transcript visible.
574
- const lines = this.scroll.render(inner);
575
- this.page = Math.min(
576
- height - 3 - navigation.length - heading.length,
577
- Math.max(1, lines.length),
578
- );
579
- this.scroll.updateLayout(lines.length, this.page, () => tui.requestRender());
672
+ this.scroll.maxHeight = height - 3 - navigation.length - heading.length;
580
673
  const editing = this.mode === "custom" || this.mode === "notes";
581
- const focusLine = editing
582
- ? lines.findIndex((line) => line.includes(CURSOR_MARKER))
583
- : this.selectedLine;
584
- if ((editing || this.followSelection) && !reading && focusLine >= 0) {
585
- if (focusLine < this.scroll.scrollTop) this.scroll.scrollTo(focusLine);
586
- else if (focusLine >= this.scroll.scrollTop + this.page)
587
- this.scroll.scrollTo(focusLine - this.page + 1);
588
- }
674
+ const following = editing || this.followSelection;
675
+ this.scroll.followLine = (lines) =>
676
+ following && !reading
677
+ ? editing
678
+ ? lines.findIndex((line) => line.includes(CURSOR_MARKER))
679
+ : this.selectedLine
680
+ : undefined;
681
+ const visible = this.scroll.render(inner);
682
+ this.page = this.scroll.viewportHeight;
683
+ this.bodyTop = 1 + navigation.length + heading.length;
684
+ this.bodyHeight = visible.length;
589
685
  this.followSelection = false;
590
- const visible = lines.slice(this.scroll.scrollTop, this.scroll.scrollTop + this.page);
591
- while (visible.length < this.page) visible.push("");
686
+ const totalLines = this.scroll.totalLines;
592
687
  const row = (text: string) => {
593
688
  const fitted = truncateToWidth(text, inner, "");
594
689
  return (
@@ -598,7 +693,6 @@ export class QuestionDialog implements Component, Focusable {
598
693
  theme.fg("borderAccent", " │")
599
694
  );
600
695
  };
601
- const question = this.questions[this.tab];
602
696
  const context =
603
697
  this.mode === "notes"
604
698
  ? "Note · optional"
@@ -610,20 +704,20 @@ export class QuestionDialog implements Component, Focusable {
610
704
  ? "Full question"
611
705
  : this.isReview
612
706
  ? "Review before submitting"
613
- : question?.multiSelect
707
+ : this.current?.question.multiSelect
614
708
  ? "Choose any that apply"
615
709
  : "Choose one";
616
710
  const start = this.scroll.scrollTop;
617
- const end = Math.min(lines.length, start + this.page);
711
+ const end = Math.min(totalLines, start + this.page);
618
712
  const position =
619
- lines.length > this.page
620
- ? ` ${start > 0 ? "↑ " : ""}${start + 1}–${end} / ${lines.length}${end < lines.length ? " ↓" : ""} `
713
+ totalLines > this.page
714
+ ? ` ${start > 0 ? "↑ " : ""}${start + 1}–${end} / ${totalLines}${end < totalLines ? " ↓" : ""} `
621
715
  : "";
622
716
  return [
623
717
  this.border(
624
718
  width,
625
719
  theme.fg("accent", theme.bold(" Ask questions ")),
626
- theme.fg("muted", ` ${this.answeredCount}/${this.questions.length} answered `),
720
+ theme.fg("muted", ` ${this.answeredCount}/${this.tabs.length} answered `),
627
721
  true,
628
722
  ),
629
723
  ...navigation.map(row),
@@ -643,24 +737,37 @@ export class QuestionDialog implements Component, Focusable {
643
737
  event.shift ||
644
738
  event.alt ||
645
739
  event.ctrl ||
646
- (event.type !== "press" && event.type !== "click") ||
647
- (event.y !== 1 && event.y !== 2)
740
+ (event.type !== "press" && event.type !== "click")
648
741
  )
649
742
  return undefined;
650
- const target = this.headerTargets.find(
651
- (header) => event.x >= header.start && event.x < header.end,
652
- );
653
- if (!target) return undefined;
654
- // Claim the press so Pi delivers a click instead of starting transcript selection.
655
- if (event.type === "press" || target.tab === this.tab) return { handled: true, focus: true };
656
- // Notes use the same save-on-leave behavior as Escape in their editor.
657
- if (this.mode === "notes") {
658
- const editor = this.editor("notes");
659
- editor.onSubmit?.(editor.getExpandedText());
743
+ const header =
744
+ event.y === 1 || event.y === 2
745
+ ? this.headerTargets.find((target) => event.x >= target.start && event.x < target.end)
746
+ : undefined;
747
+ if (header) {
748
+ if (event.type === "press" || header.tab === this.tab) return { handled: true, focus: true };
749
+ this.switchTab(header.tab);
750
+ } else {
751
+ if (
752
+ event.x < 2 ||
753
+ event.x >= event.width - 2 ||
754
+ event.y < this.bodyTop ||
755
+ event.y >= this.bodyTop + this.bodyHeight
756
+ )
757
+ return undefined;
758
+ const result = this.scroll.handleMouse({
759
+ ...event,
760
+ x: event.x - 2,
761
+ y: event.y - this.bodyTop,
762
+ width: event.width - 4,
763
+ height: this.bodyHeight,
764
+ });
765
+ if (!result) return undefined;
660
766
  }
661
- this.switchTab(target.tab);
662
767
  this.options.tui.requestRender();
663
- return { handled: true, focus: true };
768
+ // Keep focus and the press/click gesture on the dialog, not a button from a
769
+ // previous render. Do not reclaim focus after submission restores Pi's editor.
770
+ return { handled: true, focus: !this.closed };
664
771
  }
665
772
 
666
773
  handleInput(data: string): void {
@@ -707,18 +814,16 @@ export class QuestionDialog implements Component, Focusable {
707
814
  tui.requestRender();
708
815
  }
709
816
 
710
- /** Enter and Escape both save the note. */
711
817
  private handleNotesInput(data: string, keys: Keys): void {
712
- const editor = this.editor("notes");
713
- if (keys.cancel || (keys.confirm && !keys.newLine)) editor.onSubmit?.(editor.getExpandedText());
714
- else editor.handleInput(data);
818
+ if (keys.cancel || (keys.confirm && !keys.newLine)) this.closeNote();
819
+ else this.activeEditor()!.handleInput(data);
715
820
  }
716
821
 
717
822
  private handleCustomInput(data: string, keys: Keys): void {
718
- const editor = this.editor("custom");
823
+ const editor = this.current!.custom;
719
824
  if (keys.cancel) this.finish(cancelledResult());
720
825
  else if (keys.newLine) editor.handleInput(data);
721
- else if (keys.confirm && !isKeyRepeat(data)) editor.onSubmit?.(editor.getExpandedText());
826
+ else if (keys.confirm && !isKeyRepeat(data)) this.submitCustom();
722
827
  else if (matchesKey(data, "ctrl+u")) editor.setText("");
723
828
  // Up and Down leave the editor at its edges, keeping the draft.
724
829
  else if (keys.up && editor.getCursor().line === 0) this.moveRow(-1);
@@ -727,8 +832,8 @@ export class QuestionDialog implements Component, Focusable {
727
832
  }
728
833
 
729
834
  private handleBrowseInput(data: string, keys: Keys): void {
730
- const multiTab = this.drafts.length > 1;
731
- const question = this.questions[this.tab];
835
+ const multiTab = this.tabs.length > 1;
836
+ const tab = this.current;
732
837
  if (keys.cancel) this.finish(cancelledResult());
733
838
  else if (multiTab && (matchesKey(data, "tab") || matchesKey(data, "right")))
734
839
  this.switchTab(this.tab + 1);
@@ -739,31 +844,29 @@ export class QuestionDialog implements Component, Focusable {
739
844
  else if (
740
845
  matchesKey(data, "space") &&
741
846
  !isKeyRepeat(data) &&
742
- question?.multiSelect &&
743
- this.rows[this.tab]! < question.options.length
847
+ tab?.question.multiSelect &&
848
+ tab.row < tab.question.options.length
744
849
  )
745
850
  this.choose();
746
851
  else if (matchesKey(data, "n") && !isKeyRepeat(data)) {
747
852
  this.mode = "notes";
748
853
  this.scroll.scrollToStart();
749
854
  this.syncFocus();
750
- } else if (matchesKey(data, "q") && question) {
855
+ } else if (matchesKey(data, "q") && tab) {
751
856
  this.mode = "question";
752
857
  this.scroll.scrollToStart();
753
858
  } else if (matchesKey(data, "p") && this.preview()) {
754
859
  this.mode = "preview";
755
860
  this.scroll.scrollToStart();
756
- } else if (/^[1-9]$/.test(data) && question) {
861
+ } else if (/^[1-9]$/.test(data) && tab) {
757
862
  const index = Number(data) - 1;
758
- if (index < question.options.length) {
759
- this.rows[this.tab] = index;
863
+ if (index < tab.question.options.length) {
864
+ tab.row = index;
760
865
  this.choose();
761
866
  }
762
- } else if (matchesKey(data, "delete") && question) {
763
- const draft = this.drafts[this.tab]!;
764
- draft.selected.clear();
765
- draft.custom = "";
766
- this.editors.get(`${this.tab}:custom`)?.setText("");
867
+ } else if (matchesKey(data, "delete") && tab) {
868
+ tab.selected.clear();
869
+ tab.custom.setText("");
767
870
  } else this.scrollInput(data);
768
871
  }
769
872
 
@@ -777,6 +880,10 @@ export class QuestionDialog implements Component, Focusable {
777
880
 
778
881
  invalidate(): void {
779
882
  this.markdown.clear();
780
- for (const editor of this.editors.values()) editor.invalidate();
883
+ this.globalNote.invalidate();
884
+ for (const tab of this.tabs) {
885
+ tab.custom.invalidate();
886
+ tab.notes.invalidate();
887
+ }
781
888
  }
782
889
  }