@juicesharp/rpiv-ask-user-question 1.0.8 → 1.0.9

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-ask-user-question",
3
- "version": "1.0.8",
3
+ "version": "1.0.9",
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",
@@ -11,13 +11,15 @@ import { ChatRowView } from "../view/components/chat-row-view.js";
11
11
  import { MultiSelectView } from "../view/components/multi-select-view.js";
12
12
  import { OptionListView } from "../view/components/option-list-view.js";
13
13
  import { PreviewBlockRenderer } from "../view/components/preview/preview-block-renderer.js";
14
+ import type { PreviewPaneProps } from "../view/components/preview/preview-pane.js";
14
15
  import { PreviewPane } from "../view/components/preview/preview-pane.js";
15
16
  import { SubmitPicker } from "../view/components/submit-picker.js";
16
17
  import { TabBar } from "../view/components/tab-bar.js";
17
18
  import type { WrappingSelectItem, WrappingSelectTheme } from "../view/components/wrapping-select.js";
18
19
  import { DialogView } from "../view/dialog-builder.js";
19
20
  import { QuestionnairePropsAdapter } from "../view/props-adapter.js";
20
- import type { TabComponents } from "../view/tab-components.js";
21
+ import type { StatefulView } from "../view/stateful-view.js";
22
+ import type { TabBodyHeights, TabComponents } from "../view/tab-components.js";
21
23
  import type { InputBuffer } from "./input-buffer.js";
22
24
  import type { PerTabSelector } from "./selectors/contract.js";
23
25
  import { selectActivePreviewPaneIndex } from "./selectors/derivations.js";
@@ -50,6 +52,28 @@ export interface QuestionnaireBuilt {
50
52
  invalidate: () => void;
51
53
  }
52
54
 
55
+ interface HeightComputers {
56
+ global: (width: number) => number;
57
+ current: (width: number) => number;
58
+ }
59
+
60
+ function previewBodyHeights(pane: PreviewPane): (width: number) => TabBodyHeights {
61
+ return (width) => ({
62
+ current: pane.naturalHeight(width),
63
+ max: pane.maxNaturalHeight(width),
64
+ });
65
+ }
66
+
67
+ function multiSelectBodyHeights(view: MultiSelectView): (width: number) => TabBodyHeights {
68
+ return (width) => {
69
+ const h = view.naturalHeight(width);
70
+ return { current: h, max: h };
71
+ };
72
+ }
73
+
74
+ const isActiveTab: PerTabSelector<boolean> = (s, ctx) =>
75
+ ctx.i === selectActivePreviewPaneIndex(s.currentTab, ctx.totalQuestions);
76
+
53
77
  /**
54
78
  * Pure factory: assembles every TUI component, the props adapter, and a
55
79
  * lifecycle handle. Session-state dependencies arrive via `getCurrentTab` and
@@ -58,133 +82,208 @@ export interface QuestionnaireBuilt {
58
82
  * no selector is invoked here.
59
83
  */
60
84
  export function buildQuestionnaire(config: QuestionnaireBuildConfig): QuestionnaireBuilt {
61
- const { tui, theme, questions, itemsByTab, isMulti, initialState, inputBuffer, getCurrentTab } = config;
62
- const totalQuestions = questions.length;
85
+ return new QuestionnaireBuilder(config).build();
86
+ }
63
87
 
64
- const selectTheme: WrappingSelectTheme = {
65
- selectedText: (t) => theme.fg("accent", theme.bold(t)),
66
- description: (t) => theme.fg("muted", t),
67
- scrollInfo: (t) => theme.fg("dim", t),
68
- };
88
+ /**
89
+ * Programming-by-intention assembly: each private method names one
90
+ * construction step from `build()`. Read top-down; the class is build-only and
91
+ * discarded once the handle is returned.
92
+ */
93
+ class QuestionnaireBuilder {
94
+ private readonly tui: QuestionnaireBuildConfig["tui"];
95
+ private readonly theme: Theme;
96
+ private readonly questions: readonly QuestionData[];
97
+ private readonly itemsByTab: ReadonlyArray<readonly WrappingSelectItem[]>;
98
+ private readonly isMulti: boolean;
99
+ private readonly initialState: QuestionnaireState;
100
+ private readonly inputBuffer: InputBuffer;
101
+ private readonly getCurrentTab: () => number;
69
102
 
70
- const chatRow = new ChatRowView({
71
- item: { kind: "chat", label: SENTINEL_LABELS.chat },
72
- theme: selectTheme,
73
- });
74
- const notesInput = new Input();
103
+ private readonly selectTheme: WrappingSelectTheme;
104
+ private readonly markdownTheme = getMarkdownTheme();
105
+ private readonly chatRow: ChatRowView;
106
+ private readonly notesInput = new Input();
107
+ private readonly getTerminalWidth = () => this.tui.terminal.columns;
75
108
 
76
- const markdownTheme = getMarkdownTheme();
77
- const getTerminalWidth = () => tui.terminal.columns;
109
+ constructor(config: QuestionnaireBuildConfig) {
110
+ this.tui = config.tui;
111
+ this.theme = config.theme;
112
+ this.questions = config.questions;
113
+ this.itemsByTab = config.itemsByTab;
114
+ this.isMulti = config.isMulti;
115
+ this.initialState = config.initialState;
116
+ this.inputBuffer = config.inputBuffer;
117
+ this.getCurrentTab = config.getCurrentTab;
118
+
119
+ this.selectTheme = this.makeSelectTheme();
120
+ this.chatRow = new ChatRowView({
121
+ item: { kind: "chat", label: SENTINEL_LABELS.chat },
122
+ theme: this.selectTheme,
123
+ });
124
+ }
78
125
 
79
- // Concrete-typed locals retained for the height callbacks
80
- // (`naturalHeight` / `maxNaturalHeight` are not on `StatefulView<P>`).
81
- const previewPanesByTab: PreviewPane[] = [];
82
- const multiSelectViewsByTab: (MultiSelectView | undefined)[] = [];
126
+ build(): QuestionnaireBuilt {
127
+ const tabs = this.buildTabComponents();
128
+ const submitPicker = this.buildSubmitPicker();
129
+ const tabBar = this.buildTabBar();
130
+ const heights = this.buildHeightComputers(tabs);
131
+ const dialog = this.buildDialog(tabs, submitPicker, tabBar, heights);
132
+ const globalBindings = this.buildGlobalBindings(dialog, submitPicker, tabBar);
133
+ const perTabBindings = this.buildPerTabBindings();
134
+ const adapter = this.buildAdapter(tabs, globalBindings, perTabBindings);
135
+ return this.handle(adapter, dialog);
136
+ }
83
137
 
84
- const tabsByIndex: ReadonlyArray<TabComponents> = questions.map((q, i) => {
85
- const optionList = new OptionListView({ items: itemsByTab[i] ?? [], theme: selectTheme });
86
- const previewBlock = new PreviewBlockRenderer({ question: q, theme, markdownTheme });
138
+ private makeSelectTheme(): WrappingSelectTheme {
139
+ const t = this.theme;
140
+ return {
141
+ selectedText: (s) => t.fg("accent", t.bold(s)),
142
+ description: (s) => t.fg("muted", s),
143
+ scrollInfo: (s) => t.fg("dim", s),
144
+ };
145
+ }
146
+
147
+ private buildTabComponents(): ReadonlyArray<TabComponents> {
148
+ return this.questions.map((q, i) => this.buildTabFor(q, i));
149
+ }
150
+
151
+ private buildTabFor(question: QuestionData, index: number): TabComponents {
152
+ const optionList = new OptionListView({
153
+ items: this.itemsByTab[index] ?? [],
154
+ theme: this.selectTheme,
155
+ });
156
+ const previewBlock = new PreviewBlockRenderer({
157
+ question,
158
+ theme: this.theme,
159
+ markdownTheme: this.markdownTheme,
160
+ });
87
161
  const preview = new PreviewPane({
88
- question: q,
89
- getTerminalWidth,
162
+ question,
163
+ getTerminalWidth: this.getTerminalWidth,
90
164
  optionListView: optionList,
91
165
  previewBlock,
92
166
  });
93
- const multiSelect = q.multiSelect ? new MultiSelectView(theme, q) : undefined;
167
+ const multiSelect = question.multiSelect ? new MultiSelectView(this.theme, question) : undefined;
168
+ const bodyHeights = this.buildBodyHeights(question, preview, multiSelect);
169
+ return { optionList, preview, multiSelect, bodyHeights };
170
+ }
94
171
 
95
- previewPanesByTab.push(preview);
96
- multiSelectViewsByTab.push(multiSelect);
172
+ private buildBodyHeights(
173
+ question: QuestionData,
174
+ preview: PreviewPane,
175
+ multiSelect: MultiSelectView | undefined,
176
+ ): (width: number) => TabBodyHeights {
177
+ return question.multiSelect ? multiSelectBodyHeights(multiSelect!) : previewBodyHeights(preview);
178
+ }
97
179
 
98
- return { optionList, preview, multiSelect };
99
- });
180
+ private buildSubmitPicker(): SubmitPicker | undefined {
181
+ return this.isMulti ? new SubmitPicker(this.theme) : undefined;
182
+ }
100
183
 
101
- const submitPicker = isMulti ? new SubmitPicker(theme) : undefined;
102
- const tabBar = isMulti ? new TabBar(theme) : undefined;
103
-
104
- const computeGlobalContentHeight = (width: number): number => {
105
- let max = 0;
106
- for (let i = 0; i < questions.length; i++) {
107
- const q = questions[i];
108
- const h = q?.multiSelect
109
- ? (multiSelectViewsByTab[i]?.naturalHeight(width) ?? 0)
110
- : (previewPanesByTab[i]?.maxNaturalHeight(width) ?? 0);
111
- if (h > max) max = h;
112
- }
113
- return Math.max(1, max);
114
- };
115
- const computeCurrentContentHeight = (width: number): number => {
116
- const idx = Math.min(getCurrentTab(), questions.length - 1);
117
- const q = questions[idx];
118
- if (!q) return 0;
119
- const h = q.multiSelect
120
- ? (multiSelectViewsByTab[idx]?.naturalHeight(width) ?? 0)
121
- : (previewPanesByTab[idx]?.naturalHeight(width) ?? 0);
122
- return Math.max(0, h);
123
- };
184
+ private buildTabBar(): TabBar | undefined {
185
+ return this.isMulti ? new TabBar(this.theme) : undefined;
186
+ }
124
187
 
125
- const initialActivePreviewPane =
126
- previewPanesByTab[selectActivePreviewPaneIndex(initialState.currentTab, totalQuestions)] ?? previewPanesByTab[0]!;
127
-
128
- const dialog = new DialogView(
129
- {
130
- theme,
131
- questions,
132
- tabBar,
133
- notesInput,
134
- chatRow,
135
- isMulti,
136
- tabsByIndex,
137
- submitPicker,
138
- getBodyHeight: computeGlobalContentHeight,
139
- getCurrentBodyHeight: computeCurrentContentHeight,
140
- },
141
- { state: initialState, activePreviewPane: initialActivePreviewPane },
142
- );
143
-
144
- const globalBindings: ReadonlyArray<BoundGlobalBinding> = [
145
- globalBinding({ component: dialog, select: selectDialogProps }),
146
- globalBinding({ component: chatRow, select: selectChatRowProps }),
147
- ...(submitPicker ? [globalBinding({ component: submitPicker, select: selectSubmitPickerProps })] : []),
148
- ...(tabBar ? [globalBinding({ component: tabBar, select: selectTabBarProps })] : []),
149
- ];
150
-
151
- const isActiveTab: PerTabSelector<boolean> = (s, ctx) => {
152
- const paneIdx = ctx.totalQuestions <= 0 ? 0 : Math.min(s.currentTab, ctx.totalQuestions - 1);
153
- return ctx.i === paneIdx;
154
- };
188
+ private buildHeightComputers(tabs: ReadonlyArray<TabComponents>): HeightComputers {
189
+ const global = (width: number): number => {
190
+ let max = 0;
191
+ for (const tab of tabs) {
192
+ const h = tab.bodyHeights(width).max;
193
+ if (h > max) max = h;
194
+ }
195
+ return Math.max(1, max);
196
+ };
197
+ const current = (width: number): number => {
198
+ const idx = Math.min(this.getCurrentTab(), tabs.length - 1);
199
+ return Math.max(0, tabs[idx]?.bodyHeights(width).current ?? 0);
200
+ };
201
+ return { global, current };
202
+ }
155
203
 
156
- const perTabBindings: ReadonlyArray<BoundPerTabBinding> = [
157
- perTabBinding({
158
- resolve: (tab) => tab.optionList,
159
- predicate: isActiveTab,
160
- select: selectOptionListProps,
161
- }),
162
- perTabBinding({
163
- resolve: (tab) => tab.preview,
164
- predicate: isActiveTab,
165
- select: selectPreviewPaneProps,
166
- }),
167
- perTabBinding({
168
- resolve: (tab) => tab.multiSelect,
169
- select: selectMultiSelectProps,
170
- }),
171
- ];
172
-
173
- const adapter = new QuestionnairePropsAdapter({
174
- tui,
175
- questions,
176
- itemsByTab,
177
- tabsByIndex,
178
- inputBuffer,
179
- globalBindings,
180
- perTabBindings,
181
- extraInvalidatables: [notesInput],
182
- });
204
+ private pickInitialActivePreview(tabs: ReadonlyArray<TabComponents>): StatefulView<PreviewPaneProps> {
205
+ const idx = selectActivePreviewPaneIndex(this.initialState.currentTab, this.questions.length);
206
+ return tabs[idx]?.preview ?? tabs[0]!.preview;
207
+ }
183
208
 
184
- return {
185
- adapter,
186
- notesInput,
187
- render: (w) => dialog.render(w),
188
- invalidate: () => adapter.invalidate(),
189
- };
209
+ private buildDialog(
210
+ tabs: ReadonlyArray<TabComponents>,
211
+ submitPicker: SubmitPicker | undefined,
212
+ tabBar: TabBar | undefined,
213
+ heights: HeightComputers,
214
+ ): DialogView {
215
+ return new DialogView(
216
+ {
217
+ theme: this.theme,
218
+ questions: this.questions,
219
+ tabBar,
220
+ notesInput: this.notesInput,
221
+ chatRow: this.chatRow,
222
+ isMulti: this.isMulti,
223
+ tabsByIndex: tabs,
224
+ submitPicker,
225
+ getBodyHeight: heights.global,
226
+ getCurrentBodyHeight: heights.current,
227
+ },
228
+ { state: this.initialState, activePreviewPane: this.pickInitialActivePreview(tabs) },
229
+ );
230
+ }
231
+
232
+ private buildGlobalBindings(
233
+ dialog: DialogView,
234
+ submitPicker: SubmitPicker | undefined,
235
+ tabBar: TabBar | undefined,
236
+ ): ReadonlyArray<BoundGlobalBinding> {
237
+ return [
238
+ globalBinding({ component: dialog, select: selectDialogProps }),
239
+ globalBinding({ component: this.chatRow, select: selectChatRowProps }),
240
+ ...(submitPicker ? [globalBinding({ component: submitPicker, select: selectSubmitPickerProps })] : []),
241
+ ...(tabBar ? [globalBinding({ component: tabBar, select: selectTabBarProps })] : []),
242
+ ];
243
+ }
244
+
245
+ private buildPerTabBindings(): ReadonlyArray<BoundPerTabBinding> {
246
+ return [
247
+ perTabBinding({
248
+ resolve: (tab) => tab.optionList,
249
+ predicate: isActiveTab,
250
+ select: selectOptionListProps,
251
+ }),
252
+ perTabBinding({
253
+ resolve: (tab) => tab.preview,
254
+ predicate: isActiveTab,
255
+ select: selectPreviewPaneProps,
256
+ }),
257
+ perTabBinding({
258
+ resolve: (tab) => tab.multiSelect,
259
+ select: selectMultiSelectProps,
260
+ }),
261
+ ];
262
+ }
263
+
264
+ private buildAdapter(
265
+ tabs: ReadonlyArray<TabComponents>,
266
+ globalBindings: ReadonlyArray<BoundGlobalBinding>,
267
+ perTabBindings: ReadonlyArray<BoundPerTabBinding>,
268
+ ): QuestionnairePropsAdapter {
269
+ return new QuestionnairePropsAdapter({
270
+ tui: this.tui,
271
+ questions: this.questions,
272
+ itemsByTab: this.itemsByTab,
273
+ tabsByIndex: tabs,
274
+ inputBuffer: this.inputBuffer,
275
+ globalBindings,
276
+ perTabBindings,
277
+ extraInvalidatables: [this.notesInput],
278
+ });
279
+ }
280
+
281
+ private handle(adapter: QuestionnairePropsAdapter, dialog: DialogView): QuestionnaireBuilt {
282
+ return {
283
+ adapter,
284
+ notesInput: this.notesInput,
285
+ render: (w) => dialog.render(w),
286
+ invalidate: () => adapter.invalidate(),
287
+ };
288
+ }
190
289
  }
@@ -28,6 +28,7 @@ export type QuestionnaireAction =
28
28
  * `[chat, option0, …, optionLast]`.
29
29
  */
30
30
  | { kind: "focus_options"; optionIndex: number }
31
+ | { kind: "notes_forward"; data: string }
31
32
  | { kind: "ignore" };
32
33
 
33
34
  export interface QuestionnaireKeybindings {
@@ -149,7 +150,7 @@ export function routeKey(data: string, state: QuestionnaireState, runtime: Quest
149
150
  if (state.notesVisible) {
150
151
  if (kb.matches(data, KEYBIND_CANCEL)) return { kind: "notes_exit" };
151
152
  if (kb.matches(data, KEYBIND_CONFIRM)) return { kind: "notes_exit" };
152
- return { kind: "ignore" };
153
+ return { kind: "notes_forward", data };
153
154
  }
154
155
 
155
156
  if (state.chatFocused) {
@@ -39,6 +39,7 @@ function initialState(): QuestionnaireState {
39
39
  notesByTab: new Map(),
40
40
  focusedOptionHasPreview: false,
41
41
  submitChoiceIndex: 0,
42
+ notesDraft: "",
42
43
  };
43
44
  }
44
45
 
@@ -96,23 +97,7 @@ export class QuestionnaireSession {
96
97
  this.viewAdapter.apply(this.state);
97
98
  }
98
99
 
99
- /**
100
- * Single dispatch entry point. Two-pass when `notesVisible` is active — once to probe
101
- * for `notes_exit`, then forward to the Input on every other key. The head-guard pattern
102
- * is load-bearing (any non-Esc/Enter key must reach `Input.handleInput`).
103
- */
104
100
  dispatch(data: string): void {
105
- if (this.state.notesVisible) {
106
- const preAction = routeKey(data, this.state, this.runtime());
107
- if (preAction.kind === "notes_exit") {
108
- this.commit(preAction);
109
- return;
110
- }
111
- this.notesInput.handleInput(data);
112
- this.tui.requestRender();
113
- return;
114
- }
115
-
116
101
  const action = routeKey(data, this.state, this.runtime());
117
102
  if (action.kind === "ignore") {
118
103
  this.handleIgnoreInline(data);
@@ -125,9 +110,15 @@ export class QuestionnaireSession {
125
110
  const result = reduce(this.state, action, this.applyContext());
126
111
  this.state = result.state;
127
112
  for (const effect of result.effects) this.runEffect(effect);
113
+ this.state = this.mirrorNotesDraft(this.state);
128
114
  this.viewAdapter.apply(this.state);
129
115
  }
130
116
 
117
+ private mirrorNotesDraft(s: QuestionnaireState): QuestionnaireState {
118
+ const draft = this.notesInput.getValue();
119
+ return s.notesDraft === draft ? s : { ...s, notesDraft: draft };
120
+ }
121
+
131
122
  private runEffect(effect: Effect): void {
132
123
  switch (effect.kind) {
133
124
  case "set_input_buffer":
@@ -142,6 +133,9 @@ export class QuestionnaireSession {
142
133
  case "set_notes_focused":
143
134
  this.notesInput.focused = effect.focused;
144
135
  return;
136
+ case "forward_notes_keystroke":
137
+ this.notesInput.handleInput(effect.data);
138
+ return;
145
139
  case "done":
146
140
  this.done(effect.result);
147
141
  return;
@@ -179,7 +173,6 @@ export class QuestionnaireSession {
179
173
  return {
180
174
  questions: this.questions,
181
175
  itemsByTab: this.itemsByTab,
182
- pendingNotesValue: this.notesInput.getValue().trim(),
183
176
  };
184
177
  }
185
178
 
@@ -5,18 +5,10 @@ import { ROW_INTENT_META } from "./row-intent.js";
5
5
  import { computeFocusedOptionHasPreview } from "./selectors/derivations.js";
6
6
  import type { QuestionnaireState } from "./state.js";
7
7
 
8
- /**
9
- * Per-dispatch context that doesn't live on canonical state. Captured by the runtime each
10
- * tick (`pendingNotesValue` is `notesInput.getValue().trim()`; `itemsByTab` is constant for
11
- * the session lifetime). The reducer never touches a live component — every IO call is
12
- * emitted as an `Effect` in the result.
13
- */
8
+ /** Session-lifetime constants. No live-component reads — peripheral values live on canonical state. */
14
9
  export interface ApplyContext {
15
10
  questions: readonly QuestionData[];
16
11
  itemsByTab: ReadonlyArray<readonly WrappingSelectItem[]>;
17
- /** Trimmed notes input value at dispatch time. The reducer uses this for `notes_exit`
18
- * to decide whether to merge notes into the current answer or delete pending notes. */
19
- pendingNotesValue: string;
20
12
  }
21
13
 
22
14
  /**
@@ -30,6 +22,7 @@ export type Effect =
30
22
  | { kind: "clear_input_buffer" }
31
23
  | { kind: "set_notes_value"; value: string }
32
24
  | { kind: "set_notes_focused"; focused: boolean }
25
+ | { kind: "forward_notes_keystroke"; data: string }
33
26
  | { kind: "done"; result: QuestionnaireResult };
34
27
 
35
28
  export interface ApplyResult {
@@ -96,6 +89,7 @@ function persistMultiSelectAnswer(state: QuestionnaireState, ctx: ApplyContext):
96
89
  }
97
90
 
98
91
  function switchTabResult(state: QuestionnaireState, nextTab: number, ctx: ApplyContext): ApplyResult {
92
+ const notesValue = state.notesByTab.get(nextTab) ?? state.answers.get(nextTab)?.notes ?? "";
99
93
  const transitioned: QuestionnaireState = {
100
94
  ...state,
101
95
  currentTab: nextTab,
@@ -105,9 +99,9 @@ function switchTabResult(state: QuestionnaireState, nextTab: number, ctx: ApplyC
105
99
  chatFocused: false,
106
100
  submitChoiceIndex: 0,
107
101
  multiSelectChecked: syncMultiSelectFromAnswers(state.answers, ctx.questions, nextTab),
102
+ notesDraft: notesValue,
108
103
  };
109
104
  const finalState = withFocusedOptionHasPreview(transitioned, ctx.questions);
110
- const notesValue = state.notesByTab.get(nextTab) ?? state.answers.get(nextTab)?.notes ?? "";
111
105
  return {
112
106
  state: finalState,
113
107
  effects: [
@@ -123,142 +117,174 @@ function doneFor(state: QuestionnaireState, ctx: ApplyContext, cancelled: boolea
123
117
  }
124
118
 
125
119
  /**
126
- * Pure reducer: given (state, action, ctx) returns new state + a list of declarative IO
127
- * effects. Mirrors `rpiv-todo`'s `applyTaskMutation`.
128
- *
129
- * Actions NOT routed through this reducer (handled by the runtime directly):
130
- * - `ignore` — per-keystroke input-buffer mutation; no canonical-state change. The runtime
131
- * mutates the session-owned `InputBuffer` cell directly via `handleIgnoreInline`.
132
- * - `notes_visible` two-pass forward — the runtime probes the dispatcher for `notes_exit`;
133
- * every other key forwards to the pi-tui `Input` without reducer involvement.
120
+ * Per-kind handler signature: action payload narrows to the matching union member
121
+ * via `Extract`, so handlers consume fully-typed actions without `as` casts.
134
122
  */
135
- export function reduce(state: QuestionnaireState, action: QuestionnaireAction, ctx: ApplyContext): ApplyResult {
136
- switch (action.kind) {
137
- case "nav": {
138
- const items = ctx.itemsByTab[state.currentTab] ?? [];
139
- const item = items[action.nextIndex];
140
- const inputMode = item ? ROW_INTENT_META[item.kind].activatesInputMode : false;
141
- const next = withFocusedOptionHasPreview(
142
- { ...state, optionIndex: action.nextIndex, inputMode },
143
- ctx.questions,
144
- );
145
- if (!inputMode) {
146
- return { state: next, effects: [{ kind: "clear_input_buffer" }] };
147
- }
148
- const prior = state.answers.get(state.currentTab);
149
- if (prior?.kind === "custom" && typeof prior.answer === "string") {
150
- return { state: next, effects: [{ kind: "set_input_buffer", value: prior.answer }] };
151
- }
152
- return { state: next, effects: [] };
153
- }
154
- case "tab_switch": {
155
- return switchTabResult(state, action.nextTab, ctx);
156
- }
157
- case "confirm": {
158
- let answer = action.answer;
159
- if (answer.kind === "option" && answer.answer) {
160
- const q = ctx.questions[answer.questionIndex];
161
- const matched = q?.options.find((o) => o.label === answer.answer);
162
- if (matched?.preview && matched.preview.length > 0) {
163
- answer = { ...answer, preview: matched.preview };
164
- }
165
- }
166
- const pendingNotes = state.notesByTab.get(answer.questionIndex);
167
- if (pendingNotes && pendingNotes.length > 0) {
168
- answer = { ...answer, notes: pendingNotes };
169
- }
170
- const answers = new Map(state.answers);
171
- answers.set(answer.questionIndex, answer);
172
- const next: QuestionnaireState = { ...state, answers };
173
- if (answer.kind === "chat") return doneFor(next, ctx, false);
174
- if (action.autoAdvanceTab !== undefined) return switchTabResult(next, action.autoAdvanceTab, ctx);
175
- return doneFor(next, ctx, false);
176
- }
177
- case "toggle": {
178
- const checked = new Set(state.multiSelectChecked);
179
- if (checked.has(action.index)) checked.delete(action.index);
180
- else checked.add(action.index);
181
- const intermediate: QuestionnaireState = { ...state, multiSelectChecked: checked };
182
- const answers = persistMultiSelectAnswer(intermediate, ctx);
183
- return { state: { ...intermediate, answers }, effects: [] };
184
- }
185
- case "multi_confirm": {
186
- const q = ctx.questions[state.currentTab];
187
- if (!q) return { state, effects: [] };
188
- const pendingNotes = state.notesByTab.get(state.currentTab);
189
- const answers = new Map(state.answers);
190
- answers.set(state.currentTab, {
191
- questionIndex: state.currentTab,
192
- question: q.question,
193
- kind: "multi",
194
- answer: null,
195
- selected: action.selected,
196
- ...(pendingNotes && pendingNotes.length > 0 ? { notes: pendingNotes } : {}),
197
- });
198
- const synced: QuestionnaireState = {
199
- ...state,
200
- answers,
201
- multiSelectChecked: syncMultiSelectFromAnswers(answers, ctx.questions, state.currentTab),
202
- };
203
- if (action.autoAdvanceTab !== undefined) return switchTabResult(synced, action.autoAdvanceTab, ctx);
204
- return doneFor(synced, ctx, false);
205
- }
206
- case "cancel": {
207
- return doneFor(state, ctx, true);
208
- }
209
- case "notes_enter": {
210
- const value = state.answers.get(state.currentTab)?.notes ?? "";
211
- return {
212
- state: { ...state, notesVisible: true },
213
- effects: [
214
- { kind: "set_notes_value", value },
215
- { kind: "set_notes_focused", focused: true },
216
- ],
217
- };
218
- }
219
- case "notes_exit": {
220
- const trimmed = ctx.pendingNotesValue;
221
- const notes = new Map(state.notesByTab);
222
- const answers = new Map(state.answers);
223
- if (trimmed.length === 0) {
224
- notes.delete(state.currentTab);
225
- const prev = answers.get(state.currentTab);
226
- if (prev?.notes) {
227
- const stripped = { ...prev };
228
- delete (stripped as { notes?: string }).notes;
229
- answers.set(state.currentTab, stripped);
230
- }
231
- } else {
232
- notes.set(state.currentTab, trimmed);
233
- const prev = answers.get(state.currentTab);
234
- if (prev) answers.set(state.currentTab, { ...prev, notes: trimmed });
235
- }
236
- return {
237
- state: { ...state, notesByTab: notes, answers, notesVisible: false },
238
- effects: [{ kind: "set_notes_focused", focused: false }],
239
- };
240
- }
241
- case "submit": {
242
- return doneFor(state, ctx, false);
243
- }
244
- case "submit_nav": {
245
- return { state: { ...state, submitChoiceIndex: action.nextIndex }, effects: [] };
246
- }
247
- case "focus_chat": {
248
- return { state: { ...state, chatFocused: true }, effects: [] };
249
- }
250
- case "focus_options": {
251
- const items = ctx.itemsByTab[state.currentTab] ?? [];
252
- const focused = items[action.optionIndex];
253
- const inputMode = focused ? ROW_INTENT_META[focused.kind].activatesInputMode : false;
254
- const next = withFocusedOptionHasPreview(
255
- { ...state, chatFocused: false, optionIndex: action.optionIndex, inputMode },
256
- ctx.questions,
257
- );
258
- return { state: next, effects: inputMode ? [] : [{ kind: "clear_input_buffer" }] };
123
+ type Handler<K extends QuestionnaireAction["kind"]> = (
124
+ state: QuestionnaireState,
125
+ action: Extract<QuestionnaireAction, { kind: K }>,
126
+ ctx: ApplyContext,
127
+ ) => ApplyResult;
128
+
129
+ const navHandler: Handler<"nav"> = (state, action, ctx) => {
130
+ const items = ctx.itemsByTab[state.currentTab] ?? [];
131
+ const item = items[action.nextIndex];
132
+ const inputMode = item ? ROW_INTENT_META[item.kind].activatesInputMode : false;
133
+ const next = withFocusedOptionHasPreview({ ...state, optionIndex: action.nextIndex, inputMode }, ctx.questions);
134
+ if (!inputMode) {
135
+ return { state: next, effects: [{ kind: "clear_input_buffer" }] };
136
+ }
137
+ const prior = state.answers.get(state.currentTab);
138
+ if (prior?.kind === "custom" && typeof prior.answer === "string") {
139
+ return { state: next, effects: [{ kind: "set_input_buffer", value: prior.answer }] };
140
+ }
141
+ return { state: next, effects: [] };
142
+ };
143
+
144
+ const tabSwitchHandler: Handler<"tab_switch"> = (state, action, ctx) => switchTabResult(state, action.nextTab, ctx);
145
+
146
+ const confirmHandler: Handler<"confirm"> = (state, action, ctx) => {
147
+ let answer = action.answer;
148
+ if (answer.kind === "option" && answer.answer) {
149
+ const q = ctx.questions[answer.questionIndex];
150
+ const matched = q?.options.find((o) => o.label === answer.answer);
151
+ if (matched?.preview && matched.preview.length > 0) {
152
+ answer = { ...answer, preview: matched.preview };
259
153
  }
260
- case "ignore": {
261
- return { state, effects: [] };
154
+ }
155
+ const pendingNotes = state.notesByTab.get(answer.questionIndex);
156
+ if (pendingNotes && pendingNotes.length > 0) {
157
+ answer = { ...answer, notes: pendingNotes };
158
+ }
159
+ const answers = new Map(state.answers);
160
+ answers.set(answer.questionIndex, answer);
161
+ const next: QuestionnaireState = { ...state, answers };
162
+ if (answer.kind === "chat") return doneFor(next, ctx, false);
163
+ if (action.autoAdvanceTab !== undefined) return switchTabResult(next, action.autoAdvanceTab, ctx);
164
+ return doneFor(next, ctx, false);
165
+ };
166
+
167
+ const toggleHandler: Handler<"toggle"> = (state, action, ctx) => {
168
+ const checked = new Set(state.multiSelectChecked);
169
+ if (checked.has(action.index)) checked.delete(action.index);
170
+ else checked.add(action.index);
171
+ const intermediate: QuestionnaireState = { ...state, multiSelectChecked: checked };
172
+ const answers = persistMultiSelectAnswer(intermediate, ctx);
173
+ return { state: { ...intermediate, answers }, effects: [] };
174
+ };
175
+
176
+ const multiConfirmHandler: Handler<"multi_confirm"> = (state, action, ctx) => {
177
+ const q = ctx.questions[state.currentTab];
178
+ if (!q) return { state, effects: [] };
179
+ const pendingNotes = state.notesByTab.get(state.currentTab);
180
+ const answers = new Map(state.answers);
181
+ answers.set(state.currentTab, {
182
+ questionIndex: state.currentTab,
183
+ question: q.question,
184
+ kind: "multi",
185
+ answer: null,
186
+ selected: action.selected,
187
+ ...(pendingNotes && pendingNotes.length > 0 ? { notes: pendingNotes } : {}),
188
+ });
189
+ const synced: QuestionnaireState = {
190
+ ...state,
191
+ answers,
192
+ multiSelectChecked: syncMultiSelectFromAnswers(answers, ctx.questions, state.currentTab),
193
+ };
194
+ if (action.autoAdvanceTab !== undefined) return switchTabResult(synced, action.autoAdvanceTab, ctx);
195
+ return doneFor(synced, ctx, false);
196
+ };
197
+
198
+ const notesEnterHandler: Handler<"notes_enter"> = (state, _action, _ctx) => {
199
+ const value = state.answers.get(state.currentTab)?.notes ?? "";
200
+ return {
201
+ state: { ...state, notesVisible: true, notesDraft: value },
202
+ effects: [
203
+ { kind: "set_notes_value", value },
204
+ { kind: "set_notes_focused", focused: true },
205
+ ],
206
+ };
207
+ };
208
+
209
+ const notesExitHandler: Handler<"notes_exit"> = (state, _action, _ctx) => {
210
+ const trimmed = state.notesDraft.trim();
211
+ const notes = new Map(state.notesByTab);
212
+ const answers = new Map(state.answers);
213
+ if (trimmed.length === 0) {
214
+ notes.delete(state.currentTab);
215
+ const prev = answers.get(state.currentTab);
216
+ if (prev?.notes) {
217
+ const stripped = { ...prev };
218
+ delete (stripped as { notes?: string }).notes;
219
+ answers.set(state.currentTab, stripped);
262
220
  }
221
+ } else {
222
+ notes.set(state.currentTab, trimmed);
223
+ const prev = answers.get(state.currentTab);
224
+ if (prev) answers.set(state.currentTab, { ...prev, notes: trimmed });
263
225
  }
226
+ return {
227
+ state: { ...state, notesByTab: notes, answers, notesVisible: false },
228
+ effects: [{ kind: "set_notes_focused", focused: false }],
229
+ };
230
+ };
231
+
232
+ const focusOptionsHandler: Handler<"focus_options"> = (state, action, ctx) => {
233
+ const items = ctx.itemsByTab[state.currentTab] ?? [];
234
+ const focused = items[action.optionIndex];
235
+ const inputMode = focused ? ROW_INTENT_META[focused.kind].activatesInputMode : false;
236
+ const next = withFocusedOptionHasPreview(
237
+ { ...state, chatFocused: false, optionIndex: action.optionIndex, inputMode },
238
+ ctx.questions,
239
+ );
240
+ return { state: next, effects: inputMode ? [] : [{ kind: "clear_input_buffer" }] };
241
+ };
242
+
243
+ const cancelHandler: Handler<"cancel"> = (s, _a, c) => doneFor(s, c, true);
244
+ const submitHandler: Handler<"submit"> = (s, _a, c) => doneFor(s, c, false);
245
+ const submitNavHandler: Handler<"submit_nav"> = (s, a, _c) => ({
246
+ state: { ...s, submitChoiceIndex: a.nextIndex },
247
+ effects: [],
248
+ });
249
+ const focusChatHandler: Handler<"focus_chat"> = (s, _a, _c) => ({
250
+ state: { ...s, chatFocused: true },
251
+ effects: [],
252
+ });
253
+ const notesForwardHandler: Handler<"notes_forward"> = (s, a, _c) => ({
254
+ state: s,
255
+ effects: [{ kind: "forward_notes_keystroke", data: a.data }],
256
+ });
257
+ const ignoreHandler: Handler<"ignore"> = (s, _a, _c) => ({ state: s, effects: [] });
258
+
259
+ /**
260
+ * Compile-time-exhaustive dispatch table. `{ [K in Kind]: Handler<K> }` requires
261
+ * an entry per union member — adding a new `QuestionnaireAction` variant fails to
262
+ * compile here until a handler is registered, mirroring the `Record<RowKind, …>`
263
+ * pattern used by `ROW_INTENT_META`.
264
+ */
265
+ const HANDLERS: { [K in QuestionnaireAction["kind"]]: Handler<K> } = {
266
+ nav: navHandler,
267
+ tab_switch: tabSwitchHandler,
268
+ confirm: confirmHandler,
269
+ toggle: toggleHandler,
270
+ multi_confirm: multiConfirmHandler,
271
+ cancel: cancelHandler,
272
+ notes_enter: notesEnterHandler,
273
+ notes_exit: notesExitHandler,
274
+ notes_forward: notesForwardHandler,
275
+ submit: submitHandler,
276
+ submit_nav: submitNavHandler,
277
+ focus_chat: focusChatHandler,
278
+ focus_options: focusOptionsHandler,
279
+ ignore: ignoreHandler,
280
+ };
281
+
282
+ /**
283
+ * Pure reducer: (state, action, ctx) → (state, Effect[]). Mirrors `rpiv-todo`'s `applyTaskMutation`.
284
+ * Delegates to `HANDLERS` — per-kind handlers above are pure, named, and individually testable.
285
+ * `ignore` is also handled outside the reducer by `handleIgnoreInline` in the runtime fast path.
286
+ */
287
+ export function reduce(state: QuestionnaireState, action: QuestionnaireAction, ctx: ApplyContext): ApplyResult {
288
+ const handler = HANDLERS[action.kind] as Handler<typeof action.kind>;
289
+ return handler(state, action as never, ctx);
264
290
  }
package/state/state.ts CHANGED
@@ -23,6 +23,8 @@ export interface QuestionnaireState {
23
23
  focusedOptionHasPreview: boolean;
24
24
  /** Focused row in the Submit-tab picker (0 = Submit, 1 = Cancel). Reset on tab switch. */
25
25
  submitChoiceIndex: number;
26
+ /** Canonical mirror of the in-flight notes editor; runtime mirrors after `forward_notes_keystroke`. */
27
+ notesDraft: string;
26
28
  }
27
29
 
28
30
  /**
@@ -3,16 +3,14 @@ import type { OptionListViewProps } from "./components/option-list-view.js";
3
3
  import type { PreviewPaneProps } from "./components/preview/preview-pane.js";
4
4
  import type { StatefulView } from "./stateful-view.js";
5
5
 
6
- /**
7
- * Per-question view components, exposed to the adapter and dialog as
8
- * `StatefulView<XProps>` views (interface-only consumption). The same
9
- * runtime instances that satisfy these tightened types also satisfy their
10
- * concrete classes; `buildQuestionnaire` keeps separate concrete-typed local
11
- * arrays for the height callbacks (`naturalHeight` / `maxNaturalHeight` are
12
- * not on `StatefulView<P>`).
13
- */
6
+ export interface TabBodyHeights {
7
+ current: number;
8
+ max: number;
9
+ }
10
+
14
11
  export interface TabComponents {
15
12
  optionList: StatefulView<OptionListViewProps>;
16
13
  preview: StatefulView<PreviewPaneProps>;
17
14
  multiSelect?: StatefulView<MultiSelectViewProps>;
15
+ bodyHeights: (width: number) => TabBodyHeights;
18
16
  }