@juicesharp/rpiv-ask-user-question 1.0.1 → 1.0.2

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/dialog-builder.ts CHANGED
@@ -9,19 +9,18 @@ import { QuestionTabStrategy, SubmitTabStrategy, type TabStrategy } from "./tab-
9
9
  import type { QuestionData } from "./types.js";
10
10
  import type { WrappingSelect } from "./wrapping-select.js";
11
11
 
12
- // Hint text — these constants are also referenced by tests as substrings of the rendered
13
- // hint line. Keep them as full "contiguous substrings" of the buildHintText() output so the
14
- // `expect(joined).toContain(HINT_*)` assertions remain valid.
15
- //
16
- // Format (per UX spec):
17
- // <Single> = "Enter to select · ↑/↓ to navigate · Esc to cancel"
18
- // <Multi> = "Enter to select · ↑/↓ to navigate · Tab to switch questions · Esc to cancel"
19
- // + multiSelect = inserts " · Space to toggle"
20
- // + answered = inserts " · n to add notes"
21
- export const HINT_SINGLE = "Enter to select · ↑/↓ to navigate · Esc to cancel";
22
- export const HINT_MULTI = "Enter to select · ↑/↓ to navigate · Tab to switch questions · Esc to cancel";
23
- export const HINT_MULTISELECT_SUFFIX = " · Space to toggle";
24
- export const HINT_NOTES_SUFFIX = " · n to add notes";
12
+ // Hint phrases — single source of truth for both production (`buildHintText`) and the
13
+ // substring assertions in `dialog-container.test.ts`.
14
+ export const HINT_PART_ENTER = "Enter to select";
15
+ export const HINT_PART_NAV = "↑/↓ to navigate";
16
+ export const HINT_PART_TOGGLE = "Space to toggle";
17
+ export const HINT_PART_NOTES = "n to add notes";
18
+ export const HINT_PART_TAB = "Tab to switch questions";
19
+ export const HINT_PART_CANCEL = "Esc to cancel";
20
+ export const HINT_SINGLE = [HINT_PART_ENTER, HINT_PART_NAV, HINT_PART_CANCEL].join(" · ");
21
+ export const HINT_MULTI = [HINT_PART_ENTER, HINT_PART_NAV, HINT_PART_TAB, HINT_PART_CANCEL].join(" · ");
22
+ export const HINT_MULTISELECT_SUFFIX = ` · ${HINT_PART_TOGGLE}`;
23
+ export const HINT_NOTES_SUFFIX = ` · ${HINT_PART_NOTES}`;
25
24
  export const REVIEW_HEADING = "Review your answers";
26
25
  export const READY_PROMPT = "Ready to submit your answers?";
27
26
  export const INCOMPLETE_WARNING_PREFIX = "⚠ Answer remaining questions before submitting:";
package/dispatch.ts CHANGED
@@ -35,14 +35,12 @@ export interface QuestionnaireKeybindings {
35
35
  matches(data: string, name: string): boolean;
36
36
  }
37
37
 
38
- export type QuestionnaireDispatchState = QuestionnaireDispatchSnapshot;
39
-
40
38
  export function wrapTab(index: number, total: number): number {
41
39
  if (total <= 0) return 0;
42
40
  return ((index % total) + total) % total;
43
41
  }
44
42
 
45
- export function allAnswered(state: QuestionnaireDispatchState): boolean {
43
+ export function allAnswered(state: QuestionnaireDispatchSnapshot): boolean {
46
44
  if (state.questions.length === 0) return false;
47
45
  for (let i = 0; i < state.questions.length; i++) {
48
46
  if (!state.answers.has(i)) return false;
@@ -50,17 +48,17 @@ export function allAnswered(state: QuestionnaireDispatchState): boolean {
50
48
  return true;
51
49
  }
52
50
 
53
- function totalTabs(state: QuestionnaireDispatchState): number {
51
+ function totalTabs(state: QuestionnaireDispatchSnapshot): number {
54
52
  return state.isMulti ? state.questions.length + 1 : 1;
55
53
  }
56
54
 
57
- function computeAutoAdvanceTab(state: QuestionnaireDispatchState): number | undefined {
55
+ function computeAutoAdvanceTab(state: QuestionnaireDispatchSnapshot): number | undefined {
58
56
  if (!state.isMulti) return undefined;
59
57
  if (state.currentTab < state.questions.length - 1) return state.currentTab + 1;
60
58
  return state.questions.length;
61
59
  }
62
60
 
63
- function buildSingleSelectAnswer(state: QuestionnaireDispatchState): QuestionAnswer | null {
61
+ function buildSingleSelectAnswer(state: QuestionnaireDispatchSnapshot): QuestionAnswer | null {
64
62
  const q = state.questions[state.currentTab];
65
63
  if (!q) return null;
66
64
 
@@ -98,7 +96,7 @@ function buildSingleSelectAnswer(state: QuestionnaireDispatchState): QuestionAns
98
96
  };
99
97
  }
100
98
 
101
- function buildMultiSelected(state: QuestionnaireDispatchState): string[] {
99
+ function buildMultiSelected(state: QuestionnaireDispatchSnapshot): string[] {
102
100
  const q = state.questions[state.currentTab];
103
101
  if (!q) return [];
104
102
  const out: string[] = [];
@@ -111,7 +109,7 @@ function buildMultiSelected(state: QuestionnaireDispatchState): string[] {
111
109
  return out;
112
110
  }
113
111
 
114
- function tabSwitchAction(data: string, state: QuestionnaireDispatchState): QuestionnaireAction | null {
112
+ function tabSwitchAction(data: string, state: QuestionnaireDispatchSnapshot): QuestionnaireAction | null {
115
113
  if (!state.isMulti) return null;
116
114
  const total = totalTabs(state);
117
115
  if (matchesKey(data, Key.tab) || matchesKey(data, Key.right)) {
@@ -126,7 +124,7 @@ function tabSwitchAction(data: string, state: QuestionnaireDispatchState): Quest
126
124
  // DOWN navigation helper shared by inputMode and normal nav branches.
127
125
  // Emits focus_chat at the boundary (last item) so the host can transfer focus to the chat row
128
126
  // without mutating optionIndex — UP-from-chat then lands on items.length - 1 (continuous cycle).
129
- function nextNavOnDown(state: QuestionnaireDispatchState): QuestionnaireAction {
127
+ function nextNavOnDown(state: QuestionnaireDispatchSnapshot): QuestionnaireAction {
130
128
  if (state.items.length > 0 && state.optionIndex === state.items.length - 1) {
131
129
  return { kind: "focus_chat" };
132
130
  }
@@ -136,14 +134,14 @@ function nextNavOnDown(state: QuestionnaireDispatchState): QuestionnaireAction {
136
134
  // UP navigation helper, symmetric with nextNavOnDown. At the TOP boundary (optionIndex 0)
137
135
  // emits focus_chat so the cycle wraps `[chat, option0, …, optionLast]` — without this, UP at
138
136
  // option 0 would skip the chat row entirely (Defect 2). Above the boundary, decrement.
139
- function prevNavOnUp(state: QuestionnaireDispatchState): QuestionnaireAction {
137
+ function prevNavOnUp(state: QuestionnaireDispatchSnapshot): QuestionnaireAction {
140
138
  if (state.items.length > 0 && state.optionIndex === 0) {
141
139
  return { kind: "focus_chat" };
142
140
  }
143
141
  return { kind: "nav", nextIndex: wrapTab(state.optionIndex - 1, Math.max(1, state.items.length)) };
144
142
  }
145
143
 
146
- export function handleQuestionnaireInput(data: string, state: QuestionnaireDispatchState): QuestionnaireAction {
144
+ export function handleQuestionnaireInput(data: string, state: QuestionnaireDispatchSnapshot): QuestionnaireAction {
147
145
  const kb = state.keybindings;
148
146
 
149
147
  if (state.notesVisible) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-ask-user-question",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "description": "Pi extension: lets the model ask you a clarifying question with structured options instead of guessing",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -1,17 +1,19 @@
1
1
  import { getMarkdownTheme, type Theme } from "@mariozechner/pi-coding-agent";
2
2
  import { getKeybindings, Input } from "@mariozechner/pi-tui";
3
+ import { type ApplyContext, applyAction, type Effect } from "./apply-action.js";
3
4
  import { buildDialog, type DialogComponent } from "./dialog-builder.js";
4
- import { handleQuestionnaireInput } from "./dispatch.js";
5
+ import { handleQuestionnaireInput, type QuestionnaireAction } from "./dispatch.js";
5
6
  import { MultiSelectOptions } from "./multi-select-options.js";
6
7
  import { PreviewPane } from "./preview-pane.js";
7
8
  import {
8
- chatNumberingFor,
9
9
  computeFocusedOptionHasPreview,
10
10
  type QuestionnaireDispatchSnapshot,
11
+ type QuestionnaireState,
11
12
  } from "./questionnaire-state.js";
12
13
  import { SubmitPicker } from "./submit-picker.js";
13
14
  import { TabBar } from "./tab-bar.js";
14
- import type { QuestionAnswer, QuestionData, QuestionnaireResult, QuestionParams } from "./types.js";
15
+ import type { QuestionData, QuestionnaireResult, QuestionParams } from "./types.js";
16
+ import { QuestionnaireViewAdapter } from "./view-adapter.js";
15
17
  import { WrappingSelect, type WrappingSelectItem, type WrappingSelectTheme } from "./wrapping-select.js";
16
18
 
17
19
  const CHAT_ABOUT_THIS_LABEL = "Chat about this";
@@ -32,30 +34,29 @@ export interface QuestionnaireSessionComponent {
32
34
  handleInput(data: string): void;
33
35
  }
34
36
 
37
+ function initialState(): QuestionnaireState {
38
+ return {
39
+ currentTab: 0,
40
+ optionIndex: 0,
41
+ inputMode: false,
42
+ notesVisible: false,
43
+ chatFocused: false,
44
+ answers: new Map(),
45
+ multiSelectChecked: new Set(),
46
+ focusedOptionHasPreview: false,
47
+ submitChoiceIndex: 0,
48
+ };
49
+ }
50
+
35
51
  /**
36
- * Closes the action → state loop for the questionnaire dialog. Pure dispatcher
37
- * (`handleQuestionnaireInput`) emits actions; this class owns the state and applies
38
- * each action via a single-purpose `handle*` method, then re-projects state into all
39
- * view components via `applyState()`.
52
+ * Slim runtime: owns the canonical state cell, the two-pass `notesVisible` dispatch loop,
53
+ * and the effect runner. State transitions delegate to the pure `applyAction` reducer
54
+ * (`apply-action.ts`); UI fan-out delegates to `QuestionnaireViewAdapter` (`view-adapter.ts`).
40
55
  *
41
- * Mirrors the `rpiv-todo` reducer + thin-controller pattern.
56
+ * Mirrors the rpiv-todo "thin controller around a pure reducer" pattern.
42
57
  */
43
58
  export class QuestionnaireSession {
44
- private currentTab = 0;
45
- private optionIndex = 0;
46
- private inputMode = false;
47
- private notesVisible = false;
48
- private chatFocused = false;
49
- private submitChoiceIndex = 0;
50
- private readonly answers = new Map<number, QuestionAnswer>();
51
- private multiSelectChecked = new Set<number>();
52
- /**
53
- * Transient pre-answer notes side-band. Decoupled from `answers` so adding notes
54
- * does NOT make `answers.has(currentTab)` true (otherwise Submit-tab missing-check
55
- * + `allAnswered()` would falsely report the question as answered). Merged into the
56
- * answer at confirm time.
57
- */
58
- private readonly notesByTab = new Map<number, string>();
59
+ private state: QuestionnaireState = initialState();
59
60
 
60
61
  private readonly questions: readonly QuestionData[];
61
62
  private readonly isMulti: boolean;
@@ -67,6 +68,7 @@ export class QuestionnaireSession {
67
68
  private readonly chatList: WrappingSelect;
68
69
  private readonly notesInput: Input;
69
70
  private readonly dialog: DialogComponent;
71
+ private readonly viewAdapter: QuestionnaireViewAdapter;
70
72
 
71
73
  private readonly tui: QuestionnaireSessionConfig["tui"];
72
74
  private readonly done: QuestionnaireSessionConfig["done"];
@@ -79,15 +81,15 @@ export class QuestionnaireSession {
79
81
  this.questions = config.params.questions;
80
82
  this.isMulti = this.questions.length > 1;
81
83
  this.itemsByTab = config.itemsByTab;
84
+ // Seed from the focused option at start (cursor at tab 0, option 0). The reducer keeps
85
+ // this in sync via `withFocusedOptionHasPreview` on subsequent transitions.
86
+ this.state = { ...this.state, focusedOptionHasPreview: computeFocusedOptionHasPreview(this.questions, 0, 0) };
82
87
 
83
88
  const selectTheme: WrappingSelectTheme = {
84
89
  selectedText: (t) => config.theme.fg("accent", config.theme.bold(t)),
85
90
  description: (t) => config.theme.fg("muted", t),
86
91
  scrollInfo: (t) => config.theme.fg("dim", t),
87
92
  };
88
- // Chat row lives in its own one-item WrappingSelect. Numbering offset/total updated
89
- // on every tab switch via `applyState()` so the chat row renders as
90
- // `(N+1). Chat about this`, where N is the active tab's items.length.
91
93
  this.chatList = new WrappingSelect([{ label: CHAT_ABOUT_THIS_LABEL, isChat: true }], 1, selectTheme);
92
94
  this.notesInput = new Input();
93
95
 
@@ -105,11 +107,11 @@ export class QuestionnaireSession {
105
107
  }),
106
108
  );
107
109
 
108
- const initialState = this.snapshot();
110
+ const initialSnap = this.snapshot();
109
111
  this.multiSelectOptionsByTab = this.questions.map((q) =>
110
- q.multiSelect ? new MultiSelectOptions(config.theme, q, initialState) : undefined,
112
+ q.multiSelect ? new MultiSelectOptions(config.theme, q, initialSnap) : undefined,
111
113
  );
112
- this.submitPicker = this.isMulti ? new SubmitPicker(config.theme, initialState) : undefined;
114
+ this.submitPicker = this.isMulti ? new SubmitPicker(config.theme, initialSnap) : undefined;
113
115
  this.tabBar = this.isMulti
114
116
  ? new TabBar(
115
117
  {
@@ -125,7 +127,7 @@ export class QuestionnaireSession {
125
127
  this.dialog = buildDialog({
126
128
  theme: config.theme,
127
129
  questions: this.questions,
128
- state: this.snapshot(),
130
+ state: initialSnap,
129
131
  previewPane: this.previewPanes[0]!,
130
132
  tabBar: this.tabBar,
131
133
  notesInput: this.notesInput,
@@ -137,29 +139,37 @@ export class QuestionnaireSession {
137
139
  getCurrentBodyHeight: (w) => this.computeCurrentContentHeight(w),
138
140
  });
139
141
 
142
+ this.viewAdapter = new QuestionnaireViewAdapter({
143
+ tui: this.tui,
144
+ questions: this.questions,
145
+ itemsByTab: this.itemsByTab,
146
+ previewPanes: this.previewPanes,
147
+ chatList: this.chatList,
148
+ multiSelectOptionsByTab: this.multiSelectOptionsByTab,
149
+ submitPicker: this.submitPicker,
150
+ tabBar: this.tabBar,
151
+ dialog: this.dialog,
152
+ });
153
+
140
154
  this.component = {
141
155
  render: (w) => this.dialog.render(w),
142
156
  invalidate: () => this.dialog.invalidate(),
143
157
  handleInput: (data) => this.dispatch(data),
144
158
  };
145
159
 
146
- this.applyState();
160
+ this.viewAdapter.apply(this.state);
147
161
  }
148
162
 
149
163
  /**
150
- * Single dispatch entry point. Two-pass when `notesVisible` is active — once to
151
- * probe for `notes_exit`, then forward to the Input on every other key. The
152
- * head-guard pattern is load-bearing (any non-Esc/Enter key must reach
153
- * `Input.handleInput`).
164
+ * Single dispatch entry point. Two-pass when `notesVisible` is active — once to probe
165
+ * for `notes_exit`, then forward to the Input on every other key. The head-guard pattern
166
+ * is load-bearing (any non-Esc/Enter key must reach `Input.handleInput`).
154
167
  */
155
168
  dispatch(data: string): void {
156
- if (this.notesVisible) {
169
+ if (this.state.notesVisible) {
157
170
  const preAction = handleQuestionnaireInput(data, this.snapshot());
158
171
  if (preAction.kind === "notes_exit") {
159
- this.commitNotes();
160
- this.notesVisible = false;
161
- this.notesInput.focused = false;
162
- this.applyState();
172
+ this.commit(preAction);
163
173
  return;
164
174
  }
165
175
  this.notesInput.handleInput(data);
@@ -168,185 +178,51 @@ export class QuestionnaireSession {
168
178
  }
169
179
 
170
180
  const action = handleQuestionnaireInput(data, this.snapshot());
171
- switch (action.kind) {
172
- case "nav":
173
- this.handleNav(action.nextIndex);
174
- return;
175
- case "tab_switch":
176
- this.handleTabSwitch(action.nextTab);
177
- return;
178
- case "confirm":
179
- this.handleConfirm(action.answer, action.autoAdvanceTab);
180
- return;
181
- case "toggle":
182
- this.handleToggle(action.index);
183
- return;
184
- case "multi_confirm":
185
- this.handleMultiConfirm(action.selected, action.autoAdvanceTab);
186
- return;
187
- case "cancel":
188
- this.handleCancel();
189
- return;
190
- case "notes_enter":
191
- this.handleNotesEnter();
192
- return;
193
- case "notes_exit":
194
- this.handleNotesExit();
181
+ if (action.kind === "ignore") {
182
+ this.handleIgnoreInline(data);
183
+ return;
184
+ }
185
+ this.commit(action);
186
+ }
187
+
188
+ private commit(action: QuestionnaireAction): void {
189
+ const result = applyAction(this.state, action, this.applyContext());
190
+ this.state = result.state;
191
+ for (const effect of result.effects) this.runEffect(effect);
192
+ this.viewAdapter.apply(this.state);
193
+ }
194
+
195
+ private runEffect(effect: Effect): void {
196
+ switch (effect.kind) {
197
+ case "set_input_buffer":
198
+ this.previewPanes[this.state.currentTab]?.setInputBuffer(effect.value);
195
199
  return;
196
- case "focus_chat":
197
- this.handleFocusChat();
200
+ case "clear_input_buffer":
201
+ this.previewPanes[this.state.currentTab]?.clearInputBuffer();
198
202
  return;
199
- case "focus_options":
200
- this.handleFocusOptions(action.optionIndex);
203
+ case "set_notes_value":
204
+ this.notesInput.setValue(effect.value);
201
205
  return;
202
- case "submit_nav":
203
- this.handleSubmitNav(action.nextIndex);
206
+ case "set_notes_focused":
207
+ this.notesInput.focused = effect.focused;
204
208
  return;
205
- case "submit":
206
- this.handleSubmit();
209
+ case "set_active_preview_pane":
210
+ this.viewAdapter.setActivePreviewPane(effect.paneIndex);
207
211
  return;
208
- case "ignore":
209
- this.handleIgnore(data);
212
+ case "done":
213
+ this.done(effect.result);
210
214
  return;
211
215
  }
212
216
  }
213
217
 
214
- snapshot(): QuestionnaireDispatchSnapshot {
215
- return {
216
- currentTab: this.currentTab,
217
- optionIndex: this.optionIndex,
218
- inputMode: this.inputMode,
219
- notesVisible: this.notesVisible,
220
- chatFocused: this.chatFocused,
221
- answers: this.answers,
222
- multiSelectChecked: this.multiSelectChecked,
223
- focusedOptionHasPreview: computeFocusedOptionHasPreview(this.questions, this.currentTab, this.optionIndex),
224
- submitChoiceIndex: this.submitChoiceIndex,
225
- keybindings: getKeybindings(),
226
- inputBuffer: this.previewPanes[this.currentTab]?.getInputBuffer() ?? "",
227
- questions: this.questions,
228
- isMulti: this.isMulti,
229
- currentItem: this.currentItem(),
230
- items: this.items(),
231
- };
232
- }
233
-
234
- private handleNav(nextIndex: number): void {
235
- this.optionIndex = nextIndex;
236
- this.inputMode = !!this.currentItem()?.isOther;
237
- const pane = this.previewPanes[this.currentTab];
238
- if (!this.inputMode) {
239
- pane?.clearInputBuffer();
240
- } else {
241
- // Entering the `isOther` row: if the prior answer was custom text, restore the
242
- // typed text so the user can edit/confirm without retyping. Mirrors the notes
243
- // restoration precedent. Idempotent — `setInputBuffer` overwrites.
244
- const prior = this.answers.get(this.currentTab);
245
- if (prior?.wasCustom && typeof prior.answer === "string") {
246
- pane?.setInputBuffer(prior.answer);
247
- }
248
- }
249
- this.applyState();
250
- }
251
-
252
- private handleTabSwitch(nextTab: number): void {
253
- this.switchTab(nextTab);
254
- }
255
-
256
- private handleConfirm(rawAnswer: QuestionAnswer, autoAdvanceTab: number | undefined): void {
257
- let answer = rawAnswer;
258
- if (!answer.wasChat && !answer.wasCustom && answer.answer) {
259
- const q = this.questions[answer.questionIndex];
260
- const matched = q?.options.find((o) => o.label === answer.answer);
261
- if (matched?.preview && matched.preview.length > 0) {
262
- answer = { ...answer, preview: matched.preview };
263
- }
264
- }
265
- const pendingNotes = this.notesByTab.get(answer.questionIndex);
266
- if (pendingNotes && pendingNotes.length > 0) {
267
- answer = { ...answer, notes: pendingNotes };
268
- }
269
- this.answers.set(answer.questionIndex, answer);
270
- if (autoAdvanceTab !== undefined) this.switchTab(autoAdvanceTab);
271
- else this.submitFinal();
272
- }
273
-
274
- private handleToggle(index: number): void {
275
- if (this.multiSelectChecked.has(index)) this.multiSelectChecked.delete(index);
276
- else this.multiSelectChecked.add(index);
277
- // Persist on every toggle so tab-switching away (without Enter on Next) doesn't
278
- // drop the in-progress selection. Submit-tab summary + tab-back restore both read
279
- // from `answers`, so this single write keeps both views consistent.
280
- this.persistMultiSelectAnswer();
281
- this.applyState();
282
- }
283
-
284
- private handleMultiConfirm(selected: string[], autoAdvanceTab: number | undefined): void {
285
- const q = this.questions[this.currentTab];
286
- if (!q) return;
287
- const pendingNotes = this.notesByTab.get(this.currentTab);
288
- this.answers.set(this.currentTab, {
289
- questionIndex: this.currentTab,
290
- question: q.question,
291
- answer: null,
292
- selected,
293
- ...(pendingNotes && pendingNotes.length > 0 ? { notes: pendingNotes } : {}),
294
- });
295
- this.syncMultiSelectFromAnswers();
296
- if (autoAdvanceTab !== undefined) this.switchTab(autoAdvanceTab);
297
- else this.submitFinal();
298
- }
299
-
300
- private handleCancel(): void {
301
- this.done({ answers: this.orderedAnswers(), cancelled: true });
302
- }
303
-
304
- private handleNotesEnter(): void {
305
- this.notesVisible = true;
306
- this.notesInput.focused = true;
307
- this.notesInput.setValue(this.answers.get(this.currentTab)?.notes ?? "");
308
- this.applyState();
309
- }
310
-
311
- private handleNotesExit(): void {
312
- this.commitNotes();
313
- this.notesVisible = false;
314
- this.notesInput.focused = false;
315
- this.applyState();
316
- }
317
-
318
- private handleFocusChat(): void {
319
- this.chatFocused = true;
320
- this.applyState();
321
- }
322
-
323
- private handleFocusOptions(optionIndex: number | undefined): void {
324
- this.chatFocused = false;
325
- // When the dispatcher carries a target index, update optionIndex too — that drives
326
- // the continuous chat ↔ options cycle (DOWN-from-chat → 0, UP-from-chat → items-1).
327
- // Without it, focus simply returns to wherever the user was (legacy contract).
328
- if (optionIndex !== undefined) {
329
- this.optionIndex = optionIndex;
330
- this.inputMode = !!this.currentItem()?.isOther;
331
- if (!this.inputMode) {
332
- this.previewPanes[this.currentTab]?.clearInputBuffer();
333
- }
334
- }
335
- this.applyState();
336
- }
337
-
338
- private handleSubmitNav(nextIndex: 0 | 1): void {
339
- this.submitChoiceIndex = nextIndex;
340
- this.applyState();
341
- }
342
-
343
- private handleSubmit(): void {
344
- this.submitFinal();
345
- }
346
-
347
- private handleIgnore(data: string): void {
348
- if (!this.inputMode) return;
349
- const pane = this.previewPanes[this.currentTab];
218
+ /**
219
+ * Inline `ignore` handler — preserves per-keystroke buffer mutation when in inputMode.
220
+ * Bypasses the reducer because no canonical state changes; bypasses the view-adapter
221
+ * because only the WrappingSelect's own buffer needs to update before the next render.
222
+ */
223
+ private handleIgnoreInline(data: string): void {
224
+ if (!this.state.inputMode) return;
225
+ const pane = this.previewPanes[this.state.currentTab];
350
226
  if (!pane) return;
351
227
  if (BACKSPACE_CHARS.has(data)) {
352
228
  pane.backspaceInput();
@@ -357,123 +233,31 @@ export class QuestionnaireSession {
357
233
  }
358
234
  }
359
235
 
360
- private items(): WrappingSelectItem[] {
361
- return this.itemsByTab[this.currentTab] ?? [];
362
- }
363
-
364
- private currentItem(): WrappingSelectItem | undefined {
365
- if (this.chatFocused) return { label: CHAT_ABOUT_THIS_LABEL, isChat: true };
366
- const arr = this.items();
367
- if (this.optionIndex < arr.length) return arr[this.optionIndex];
368
- return { label: CHAT_ABOUT_THIS_LABEL, isChat: true };
369
- }
370
-
371
- private switchTab(nextTab: number): void {
372
- this.currentTab = nextTab;
373
- this.optionIndex = 0;
374
- this.inputMode = false;
375
- this.notesVisible = false;
376
- this.chatFocused = false;
377
- this.submitChoiceIndex = 0;
378
- this.notesInput.focused = false;
379
- this.notesInput.setValue(this.notesByTab.get(this.currentTab) ?? this.answers.get(this.currentTab)?.notes ?? "");
380
- this.syncMultiSelectFromAnswers();
381
- const paneIndex = Math.min(this.currentTab, this.questions.length - 1);
382
- const nextPane = this.previewPanes[paneIndex] ?? this.previewPanes[0]!;
383
- this.dialog.setPreviewPane(nextPane);
384
- this.applyState();
385
- }
386
-
387
- private submitFinal(): void {
388
- this.done({ answers: this.orderedAnswers(), cancelled: false });
389
- }
390
-
391
- private orderedAnswers(): QuestionAnswer[] {
392
- const out: QuestionAnswer[] = [];
393
- for (let i = 0; i < this.questions.length; i++) {
394
- const a = this.answers.get(i);
395
- if (a) out.push(a);
396
- }
397
- return out;
398
- }
399
-
400
- private persistMultiSelectAnswer(): void {
401
- const q = this.questions[this.currentTab];
402
- if (!q?.multiSelect) return;
403
- const selected: string[] = [];
404
- for (let i = 0; i < q.options.length; i++) {
405
- if (this.multiSelectChecked.has(i)) selected.push(q.options[i]!.label);
406
- }
407
- if (selected.length === 0) {
408
- this.answers.delete(this.currentTab);
409
- return;
410
- }
411
- const pendingNotes = this.notesByTab.get(this.currentTab);
412
- this.answers.set(this.currentTab, {
413
- questionIndex: this.currentTab,
414
- question: q.question,
415
- answer: null,
416
- selected,
417
- ...(pendingNotes && pendingNotes.length > 0 ? { notes: pendingNotes } : {}),
418
- });
419
- }
420
-
421
- /**
422
- * Pure derivation: which row in the active tab should be marked as "previously confirmed"?
423
- * Drives the `WrappingSelect` confirmed-row indicator (label + ` ✔` in accent styling) when
424
- * the user navigates back to a question they already answered. Returns `undefined` when no
425
- * marker should be drawn — multi-select handles its own `[✔]` boxes via `multiSelectChecked`,
426
- * `wasChat` ends the dialog so it can never be re-entered, and a missing/non-matching answer
427
- * (defensive) silently skips the marker.
428
- */
429
- private confirmedIndexForCurrentTab(): { index: number; labelOverride?: string } | undefined {
430
- const q = this.questions[this.currentTab];
431
- if (!q || q.multiSelect === true) return undefined;
432
- const prior = this.answers.get(this.currentTab);
433
- if (!prior || prior.wasChat) return undefined;
434
- const items = this.itemsByTab[this.currentTab] ?? [];
435
- if (prior.wasCustom) {
436
- const otherIndex = items.findIndex((it) => it.isOther === true);
437
- if (otherIndex < 0) return undefined;
438
- return { index: otherIndex, labelOverride: prior.answer ?? "" };
439
- }
440
- if (typeof prior.answer !== "string") return undefined;
441
- const index = items.findIndex((it) => !it.isOther && !it.isChat && !it.isNext && it.label === prior.answer);
442
- if (index < 0) return undefined;
443
- return { index };
236
+ private snapshot(): QuestionnaireDispatchSnapshot {
237
+ return {
238
+ ...this.state,
239
+ keybindings: getKeybindings(),
240
+ inputBuffer: this.previewPanes[this.state.currentTab]?.getInputBuffer() ?? "",
241
+ questions: this.questions,
242
+ isMulti: this.isMulti,
243
+ currentItem: this.currentItem(),
244
+ items: this.itemsByTab[this.state.currentTab] ?? [],
245
+ };
444
246
  }
445
247
 
446
- private syncMultiSelectFromAnswers(): void {
447
- const q = this.questions[this.currentTab];
448
- if (!q?.multiSelect) {
449
- this.multiSelectChecked = new Set();
450
- return;
451
- }
452
- const saved = this.answers.get(this.currentTab);
453
- const labels = saved?.selected ?? [];
454
- const indices = new Set<number>();
455
- for (let i = 0; i < q.options.length; i++) {
456
- if (labels.includes(q.options[i]!.label)) indices.add(i);
457
- }
458
- this.multiSelectChecked = indices;
248
+ private applyContext(): ApplyContext {
249
+ return {
250
+ questions: this.questions,
251
+ itemsByTab: this.itemsByTab,
252
+ pendingNotesValue: this.notesInput.getValue().trim(),
253
+ };
459
254
  }
460
255
 
461
- private commitNotes(): void {
462
- const trimmed = this.notesInput.getValue().trim();
463
- if (!this.questions[this.currentTab]) return;
464
- if (trimmed.length === 0) {
465
- this.notesByTab.delete(this.currentTab);
466
- const prev = this.answers.get(this.currentTab);
467
- if (prev?.notes) {
468
- const next = { ...prev };
469
- delete (next as { notes?: string }).notes;
470
- this.answers.set(this.currentTab, next);
471
- }
472
- return;
473
- }
474
- this.notesByTab.set(this.currentTab, trimmed);
475
- const prev = this.answers.get(this.currentTab);
476
- if (prev) this.answers.set(this.currentTab, { ...prev, notes: trimmed });
256
+ private currentItem(): WrappingSelectItem | undefined {
257
+ if (this.state.chatFocused) return { label: CHAT_ABOUT_THIS_LABEL, isChat: true };
258
+ const arr = this.itemsByTab[this.state.currentTab] ?? [];
259
+ if (this.state.optionIndex < arr.length) return arr[this.state.optionIndex];
260
+ return { label: CHAT_ABOUT_THIS_LABEL, isChat: true };
477
261
  }
478
262
 
479
263
  private computeGlobalContentHeight(width: number): number {
@@ -489,7 +273,7 @@ export class QuestionnaireSession {
489
273
  }
490
274
 
491
275
  private computeCurrentContentHeight(width: number): number {
492
- const idx = Math.min(this.currentTab, this.questions.length - 1);
276
+ const idx = Math.min(this.state.currentTab, this.questions.length - 1);
493
277
  const q = this.questions[idx];
494
278
  if (!q) return 0;
495
279
  const h = q.multiSelect
@@ -497,53 +281,4 @@ export class QuestionnaireSession {
497
281
  : (this.previewPanes[idx]?.naturalHeight(width) ?? 0);
498
282
  return Math.max(0, h);
499
283
  }
500
-
501
- /**
502
- * Mirror current state into all `setState`-style component setters in one place.
503
- * Replaces `refreshDialog + applySelection` from the old closure.
504
- */
505
- private applyState(): void {
506
- const snap = this.snapshot();
507
- this.dialog.setState(snap);
508
-
509
- const optionsFocused = !this.notesVisible && !this.chatFocused;
510
-
511
- const pane = this.previewPanes[Math.min(this.currentTab, this.questions.length - 1)] ?? this.previewPanes[0];
512
- if (pane) {
513
- pane.setSelectedIndex(this.optionIndex);
514
- pane.setFocused(optionsFocused);
515
- pane.setNotesVisible(this.notesVisible);
516
- const confirmed = this.confirmedIndexForCurrentTab();
517
- pane.setConfirmedIndex(confirmed?.index, confirmed?.labelOverride);
518
- }
519
- this.chatList.setFocused(this.chatFocused);
520
-
521
- // StatefulComponent<DialogState> registry — both setState and setFocused driven
522
- // in one place. Replaces the historical fan-out where MSO.setState was lazy in
523
- // dialog-builder.ts while MSO.setFocused was applySelection's responsibility.
524
- for (const mso of this.multiSelectOptionsByTab) {
525
- if (!mso) continue;
526
- mso.setState(snap);
527
- mso.setFocused(optionsFocused);
528
- }
529
- if (this.submitPicker) {
530
- this.submitPicker.setState(snap);
531
- this.submitPicker.setFocused(this.currentTab === this.questions.length);
532
- }
533
-
534
- const activeTabItems = this.itemsByTab[Math.min(this.currentTab, this.questions.length - 1)] ?? [];
535
- const numbering = chatNumberingFor(activeTabItems);
536
- this.chatList.setNumbering(numbering.offset, numbering.total);
537
-
538
- if (this.tabBar) {
539
- this.tabBar.setConfig({
540
- questions: this.questions,
541
- answers: new Map(this.answers),
542
- activeTabIndex: this.currentTab,
543
- totalTabs: this.questions.length + 1,
544
- });
545
- }
546
-
547
- this.tui.requestRender();
548
- }
549
284
  }
@@ -14,6 +14,15 @@ export interface QuestionnaireState {
14
14
  chatFocused: boolean;
15
15
  answers: ReadonlyMap<number, QuestionAnswer>;
16
16
  multiSelectChecked: ReadonlySet<number>;
17
+ /**
18
+ * Pre-answer notes side-band, keyed by tab index. OPTIONAL on the canonical type to
19
+ * preserve existing test-factory shapes (`dispatch.test.ts:43-63`,
20
+ * `multi-select-options.test.ts:11-23`, `submit-picker.test.ts:13-25`); the reducer
21
+ * treats `undefined` as an empty map. Decoupled from `answers` so adding notes does NOT
22
+ * make `answers.has(currentTab)` true (otherwise Submit-tab missing-check + `allAnswered()`
23
+ * would falsely report the question as answered). Merged into the answer at confirm time.
24
+ */
25
+ notesByTab?: ReadonlyMap<number, string>;
17
26
  /**
18
27
  * True iff the currently-focused option carries a non-empty `preview` string.
19
28
  * Computed via `computeFocusedOptionHasPreview` below. Stored on state because it
@@ -81,3 +90,72 @@ export function chatNumberingFor(items: readonly WrappingSelectItem[]): {
81
90
  const count = items.filter((i) => !i.isNext).length;
82
91
  return { offset: count, total: count + 1 };
83
92
  }
93
+
94
+ /**
95
+ * Which row in the active tab should be marked as "previously confirmed"? Drives the
96
+ * `WrappingSelect` confirmed-row indicator (label + ` ✔`) when the user navigates back
97
+ * to a question they already answered. Returns `undefined` when no marker should be drawn —
98
+ * multi-select handles its own `[✔]` boxes via `multiSelectChecked`, `wasChat` ends the
99
+ * dialog so the row can never be re-entered, and a missing/non-matching answer (defensive)
100
+ * silently skips the marker.
101
+ */
102
+ export function selectConfirmedIndicator(
103
+ questions: readonly QuestionData[],
104
+ currentTab: number,
105
+ answers: ReadonlyMap<number, QuestionAnswer>,
106
+ items: readonly WrappingSelectItem[],
107
+ ): { index: number; labelOverride?: string } | undefined {
108
+ const q = questions[currentTab];
109
+ if (!q || q.multiSelect === true) return undefined;
110
+ const prior = answers.get(currentTab);
111
+ if (!prior || prior.wasChat) return undefined;
112
+ if (prior.wasCustom) {
113
+ const otherIndex = items.findIndex((it) => it.isOther === true);
114
+ if (otherIndex < 0) return undefined;
115
+ return { index: otherIndex, labelOverride: prior.answer ?? "" };
116
+ }
117
+ if (typeof prior.answer !== "string") return undefined;
118
+ const index = items.findIndex((it) => !it.isOther && !it.isChat && !it.isNext && it.label === prior.answer);
119
+ if (index < 0) return undefined;
120
+ return { index };
121
+ }
122
+
123
+ /**
124
+ * Are the focusable option rows the current focus target? False when the chat row owns focus
125
+ * or the notes input is visible. Drives the active-pointer suppression on `WrappingSelect` /
126
+ * `MultiSelectOptions` so the cursor doesn't render in two places at once.
127
+ */
128
+ export function selectOptionsFocused(state: { notesVisible: boolean; chatFocused: boolean }): boolean {
129
+ return !state.notesVisible && !state.chatFocused;
130
+ }
131
+
132
+ /**
133
+ * Index of the preview pane to display for the current tab. The Submit tab (currentTab ===
134
+ * questions.length) reuses the last question's pane purely for layout — the strategy
135
+ * machinery picks the right body component independently. Defensive against `totalQuestions === 0`.
136
+ */
137
+ export function selectActivePreviewPaneIndex(currentTab: number, totalQuestions: number): number {
138
+ if (totalQuestions <= 0) return 0;
139
+ return Math.min(currentTab, totalQuestions - 1);
140
+ }
141
+
142
+ /**
143
+ * Items array for the active tab, with the same Submit-tab clamp as `selectActivePreviewPaneIndex`.
144
+ * Falls back to an empty array if the index lands outside the items array (defensive).
145
+ */
146
+ export function selectActiveTabItems(
147
+ itemsByTab: ReadonlyArray<readonly WrappingSelectItem[]>,
148
+ currentTab: number,
149
+ totalQuestions: number,
150
+ ): readonly WrappingSelectItem[] {
151
+ const idx = selectActivePreviewPaneIndex(currentTab, totalQuestions);
152
+ return itemsByTab[idx] ?? [];
153
+ }
154
+
155
+ /**
156
+ * Is the Submit tab the active tab? Drives the `SubmitPicker.setFocused` projection so
157
+ * its active pointer renders only on the Submit tab.
158
+ */
159
+ export function selectSubmitPickerFocused(currentTab: number, totalQuestions: number): boolean {
160
+ return currentTab === totalQuestions;
161
+ }
@@ -4,15 +4,9 @@ import type { Component } from "@mariozechner/pi-tui";
4
4
  * Generic state-driven component contract. Implementers consume the full canonical
5
5
  * state via `setState`; focus is set independently via `setFocused`.
6
6
  *
7
- * Today's implementers (`MultiSelectOptions`, `SubmitPicker`) use `S = DialogState`. The
8
- * contract preserves the 2-method API frozen by `multi-select-options.test.ts:147-154`
9
- * and `submit-picker.test.ts:46-50` — those tests call `setState(state)` and
10
- * `setFocused(boolean)` separately and must continue to pass without edits.
11
- *
12
- * The benefit lives in the host: `QuestionnaireSession.applyState()` iterates a
13
- * registry of `StatefulComponent<DialogState>` instances and drives both methods in
14
- * one place. Adding a new state field no longer requires updating `applySelection`
15
- * AND `dialog-builder.ts` — the session's single registry-driven loop covers both.
7
+ * `QuestionnaireViewAdapter.apply()` iterates a registry of these and drives both
8
+ * methods in one place, so adding a new state field only requires updating the state
9
+ * shape and the components that read it.
16
10
  */
17
11
  export interface StatefulComponent<S> extends Component {
18
12
  setState(state: S): void;
package/tab-strategy.ts CHANGED
@@ -1,6 +1,17 @@
1
1
  import type { Theme } from "@mariozechner/pi-coding-agent";
2
2
  import { type Component, Container, type Input, Spacer, Text } from "@mariozechner/pi-tui";
3
- import { type DialogState, INCOMPLETE_WARNING_PREFIX, READY_PROMPT, REVIEW_HEADING } from "./dialog-builder.js";
3
+ import {
4
+ type DialogState,
5
+ HINT_PART_CANCEL,
6
+ HINT_PART_ENTER,
7
+ HINT_PART_NAV,
8
+ HINT_PART_NOTES,
9
+ HINT_PART_TAB,
10
+ HINT_PART_TOGGLE,
11
+ INCOMPLETE_WARNING_PREFIX,
12
+ READY_PROMPT,
13
+ REVIEW_HEADING,
14
+ } from "./dialog-builder.js";
4
15
  import { formatAnswerScalar } from "./format-answer.js";
5
16
  import type { MultiSelectOptions } from "./multi-select-options.js";
6
17
  import type { PreviewPane } from "./preview-pane.js";
@@ -169,22 +180,22 @@ export class SubmitTabStrategy implements TabStrategy {
169
180
  }
170
181
 
171
182
  /**
172
- * Build the controls hint line. Order is fixed so HINT_SINGLE / HINT_MULTI remain
173
- * contiguous substrings of the rendered output:
183
+ * Build the controls hint line from `HINT_PART_*` phrase tokens. Order is fixed so
184
+ * `HINT_SINGLE` / `HINT_MULTI` (the constant joins) remain contiguous substrings:
174
185
  *
175
- * Enter to select · ↑/↓ to navigate (← HINT_SINGLE prefix)
176
- * [· Space to toggle] (multiSelect only)
177
- * [· n to add notes] (single-select + preview-bearing focus)
178
- * [· Tab to switch questions] (multi-question only)
186
+ * Enter to select · ↑/↓ to navigate
187
+ * [· Space to toggle] (multiSelect only)
188
+ * [· n to add notes] (single-select + preview-bearing focus)
189
+ * [· Tab to switch questions] (multi-question only)
179
190
  * · Esc to cancel
180
191
  */
181
192
  export function buildHintText(question: QuestionData | undefined, isMulti: boolean, state: DialogState): string {
182
- const parts: string[] = ["Enter to select", "↑/↓ to navigate"];
183
- if (question?.multiSelect === true) parts.push("Space to toggle");
193
+ const parts: string[] = [HINT_PART_ENTER, HINT_PART_NAV];
194
+ if (question?.multiSelect === true) parts.push(HINT_PART_TOGGLE);
184
195
  if (question && question.multiSelect !== true && state.focusedOptionHasPreview && !state.notesVisible) {
185
- parts.push("n to add notes");
196
+ parts.push(HINT_PART_NOTES);
186
197
  }
187
- if (isMulti) parts.push("Tab to switch questions");
188
- parts.push("Esc to cancel");
198
+ if (isMulti) parts.push(HINT_PART_TAB);
199
+ parts.push(HINT_PART_CANCEL);
189
200
  return parts.join(" · ");
190
201
  }