@juicesharp/rpiv-ask-user-question 1.0.4 → 1.0.5

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.
Files changed (32) hide show
  1. package/ask-user-question.ts +11 -16
  2. package/package.json +26 -24
  3. package/{apply-action.ts → state/apply-action.ts} +6 -7
  4. package/{dispatch.ts → state/dispatch.ts} +12 -8
  5. package/{questionnaire-session.ts → state/questionnaire-session.ts} +43 -29
  6. package/state/questionnaire-state.ts +321 -0
  7. package/state/row-intent.ts +161 -0
  8. package/{types.ts → tool/types.ts} +17 -16
  9. package/view/components/chat-row-view.ts +58 -0
  10. package/{multi-select-options.ts → view/components/multi-select-options.ts} +32 -37
  11. package/view/components/option-list-view.ts +110 -0
  12. package/{markdown-content-cache.ts → view/components/preview/markdown-content-cache.ts} +1 -1
  13. package/{preview-block-renderer.ts → view/components/preview/preview-block-renderer.ts} +1 -1
  14. package/{preview-pane.ts → view/components/preview/preview-pane.ts} +40 -23
  15. package/{submit-picker.ts → view/components/submit-picker.ts} +19 -15
  16. package/view/components/tab-bar.ts +60 -0
  17. package/{wrapping-select.ts → view/components/wrapping-select.ts} +5 -4
  18. package/{dialog-builder.ts → view/dialog-builder.ts} +53 -40
  19. package/view/stateful-view.ts +38 -0
  20. package/{tab-strategy.ts → view/tab-content-strategy.ts} +19 -18
  21. package/view/view-adapter.ts +111 -0
  22. package/option-list-view.ts +0 -93
  23. package/questionnaire-state.ts +0 -161
  24. package/stateful-component.ts +0 -14
  25. package/tab-bar.ts +0 -61
  26. package/view-adapter.ts +0 -133
  27. /package/{format-answer.ts → tool/format-answer.ts} +0 -0
  28. /package/{response-envelope.ts → tool/response-envelope.ts} +0 -0
  29. /package/{validate-questionnaire.ts → tool/validate-questionnaire.ts} +0 -0
  30. /package/{body-residual-spacer.ts → view/body-residual-spacer.ts} +0 -0
  31. /package/{preview-box-renderer.ts → view/components/preview/preview-box-renderer.ts} +0 -0
  32. /package/{preview-layout-decider.ts → view/components/preview/preview-layout-decider.ts} +0 -0
@@ -1,6 +1,7 @@
1
1
  import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
2
- import { QuestionnaireSession } from "./questionnaire-session.js";
3
- import { buildQuestionnaireResponse, buildToolResult } from "./response-envelope.js";
2
+ import { QuestionnaireSession } from "./state/questionnaire-session.js";
3
+ import { ROW_INTENT_META, sentinelsToAppend } from "./state/row-intent.js";
4
+ import { buildQuestionnaireResponse, buildToolResult } from "./tool/response-envelope.js";
4
5
  import {
5
6
  MAX_OPTIONS,
6
7
  MAX_QUESTIONS,
@@ -9,14 +10,13 @@ import {
9
10
  type QuestionnaireResult,
10
11
  type QuestionParams,
11
12
  QuestionParamsSchema,
12
- SENTINEL_LABELS,
13
- } from "./types.js";
14
- import { validateQuestionnaire } from "./validate-questionnaire.js";
15
- import type { WrappingSelectItem } from "./wrapping-select.js";
13
+ } from "./tool/types.js";
14
+ import { validateQuestionnaire } from "./tool/validate-questionnaire.js";
15
+ import type { WrappingSelectItem } from "./view/components/wrapping-select.js";
16
16
 
17
17
  const ERROR_NO_UI = "Error: UI not available (running in non-interactive mode)";
18
18
 
19
- export { chatNumberingFor } from "./questionnaire-state.js";
19
+ export { chatNumberingFor } from "./state/questionnaire-state.js";
20
20
 
21
21
  export function buildItemsForQuestion(question: QuestionData): WrappingSelectItem[] {
22
22
  const items: WrappingSelectItem[] = question.options.map((o) => ({
@@ -24,16 +24,11 @@ export function buildItemsForQuestion(question: QuestionData): WrappingSelectIte
24
24
  label: o.label,
25
25
  description: o.description,
26
26
  }));
27
- // Multi-select gets a "Next" sentinel row at the bottom so `Enter` on regular option rows
28
- // can be repurposed as a per-row toggle (matching `Space`); committing + advancing to the
29
- // next tab requires moving focus onto the Next row first. Mirrors the `kind: "other"` pattern.
30
- if (question.multiSelect) return [...items, { kind: "next", label: SENTINEL_LABELS.next }];
31
- // Side-by-side preview layout pins the options column to PREVIEW_LEFT_COLUMN_MAX_WIDTH (~40
32
- // cols), which truncates inline custom-text input. CC suppresses the row in this layout for
33
- // the same reason — the "Chat about this" row remains as the free-form escape hatch.
34
27
  const hasAnyPreview = question.options.some((o) => typeof o.preview === "string" && o.preview.length > 0);
35
- if (hasAnyPreview) return items;
36
- return [...items, { kind: "other", label: SENTINEL_LABELS.other }];
28
+ for (const kind of sentinelsToAppend(question, hasAnyPreview)) {
29
+ items.push({ kind, label: ROW_INTENT_META[kind].label });
30
+ }
31
+ return items;
37
32
  }
38
33
 
39
34
  export function registerAskUserQuestionTool(pi: ExtensionAPI): void {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-ask-user-question",
3
- "version": "1.0.4",
3
+ "version": "1.0.5",
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",
@@ -26,33 +26,35 @@
26
26
  "test": "vitest run"
27
27
  },
28
28
  "files": [
29
- "apply-action.ts",
30
29
  "ask-user-question.ts",
31
- "body-residual-spacer.ts",
32
- "dialog-builder.ts",
33
- "dispatch.ts",
34
- "format-answer.ts",
35
30
  "index.ts",
36
31
  "LICENSE",
37
- "markdown-content-cache.ts",
38
- "multi-select-options.ts",
39
- "option-list-view.ts",
40
- "preview-block-renderer.ts",
41
- "preview-box-renderer.ts",
42
- "preview-layout-decider.ts",
43
- "preview-pane.ts",
44
- "questionnaire-session.ts",
45
- "questionnaire-state.ts",
46
32
  "README.md",
47
- "response-envelope.ts",
48
- "stateful-component.ts",
49
- "submit-picker.ts",
50
- "tab-bar.ts",
51
- "tab-strategy.ts",
52
- "types.ts",
53
- "validate-questionnaire.ts",
54
- "view-adapter.ts",
55
- "wrapping-select.ts"
33
+ "state/apply-action.ts",
34
+ "state/dispatch.ts",
35
+ "state/questionnaire-session.ts",
36
+ "state/questionnaire-state.ts",
37
+ "state/row-intent.ts",
38
+ "tool/format-answer.ts",
39
+ "tool/response-envelope.ts",
40
+ "tool/types.ts",
41
+ "tool/validate-questionnaire.ts",
42
+ "view/body-residual-spacer.ts",
43
+ "view/components/chat-row-view.ts",
44
+ "view/components/multi-select-options.ts",
45
+ "view/components/option-list-view.ts",
46
+ "view/components/preview/markdown-content-cache.ts",
47
+ "view/components/preview/preview-block-renderer.ts",
48
+ "view/components/preview/preview-box-renderer.ts",
49
+ "view/components/preview/preview-layout-decider.ts",
50
+ "view/components/preview/preview-pane.ts",
51
+ "view/components/submit-picker.ts",
52
+ "view/components/tab-bar.ts",
53
+ "view/components/wrapping-select.ts",
54
+ "view/dialog-builder.ts",
55
+ "view/stateful-view.ts",
56
+ "view/tab-content-strategy.ts",
57
+ "view/view-adapter.ts"
56
58
  ],
57
59
  "pi": {
58
60
  "extensions": [
@@ -1,7 +1,8 @@
1
+ import type { QuestionAnswer, QuestionData, QuestionnaireResult } from "../tool/types.js";
2
+ import type { WrappingSelectItem } from "../view/components/wrapping-select.js";
1
3
  import type { QuestionnaireAction } from "./dispatch.js";
2
4
  import { computeFocusedOptionHasPreview, type QuestionnaireState } from "./questionnaire-state.js";
3
- import type { QuestionAnswer, QuestionData, QuestionnaireResult } from "./types.js";
4
- import type { WrappingSelectItem } from "./wrapping-select.js";
5
+ import { ROW_INTENT_META } from "./row-intent.js";
5
6
 
6
7
  /**
7
8
  * Per-dispatch context that doesn't live on canonical state. Captured by the runtime each
@@ -28,7 +29,6 @@ export type Effect =
28
29
  | { kind: "clear_input_buffer" }
29
30
  | { kind: "set_notes_value"; value: string }
30
31
  | { kind: "set_notes_focused"; focused: boolean }
31
- | { kind: "set_active_preview_pane"; paneIndex: number }
32
32
  | { kind: "done"; result: QuestionnaireResult };
33
33
 
34
34
  export interface ApplyResult {
@@ -112,12 +112,10 @@ function switchTabResult(state: QuestionnaireState, nextTab: number, ctx: ApplyC
112
112
  multiSelectChecked: syncMultiSelectFromAnswers(state.answers, ctx.questions, nextTab),
113
113
  };
114
114
  const finalState = withFocusedOptionHasPreview(transitioned, ctx.questions);
115
- const paneIndex = Math.min(nextTab, Math.max(0, ctx.questions.length - 1));
116
115
  const notesValue = notesOf(state).get(nextTab) ?? state.answers.get(nextTab)?.notes ?? "";
117
116
  return {
118
117
  state: finalState,
119
118
  effects: [
120
- { kind: "set_active_preview_pane", paneIndex },
121
119
  { kind: "set_notes_focused", focused: false },
122
120
  { kind: "set_notes_value", value: notesValue },
123
121
  ],
@@ -144,7 +142,7 @@ export function applyAction(state: QuestionnaireState, action: QuestionnaireActi
144
142
  case "nav": {
145
143
  const items = ctx.itemsByTab[state.currentTab] ?? [];
146
144
  const item = items[action.nextIndex];
147
- const inputMode = item?.kind === "other";
145
+ const inputMode = item ? ROW_INTENT_META[item.kind].activatesInputMode : false;
148
146
  const next = withFocusedOptionHasPreview(
149
147
  { ...state, optionIndex: action.nextIndex, inputMode },
150
148
  ctx.questions,
@@ -260,7 +258,8 @@ export function applyAction(state: QuestionnaireState, action: QuestionnaireActi
260
258
  if (action.optionIndex !== undefined) {
261
259
  optionIndex = action.optionIndex;
262
260
  const items = ctx.itemsByTab[state.currentTab] ?? [];
263
- inputMode = items[optionIndex]?.kind === "other";
261
+ const focused = items[optionIndex];
262
+ inputMode = focused ? ROW_INTENT_META[focused.kind].activatesInputMode : false;
264
263
  if (!inputMode) effects = [{ kind: "clear_input_buffer" }];
265
264
  }
266
265
  const next = withFocusedOptionHasPreview(
@@ -1,6 +1,7 @@
1
1
  import { Key, matchesKey } from "@mariozechner/pi-tui";
2
+ import type { QuestionAnswer } from "../tool/types.js";
2
3
  import type { QuestionnaireDispatchSnapshot } from "./questionnaire-state.js";
3
- import type { QuestionAnswer } from "./types.js";
4
+ import { ROW_INTENT_META } from "./row-intent.js";
4
5
 
5
6
  const KEYBIND_UP = "tui.select.up";
6
7
  const KEYBIND_DOWN = "tui.select.down";
@@ -228,18 +229,21 @@ export function handleQuestionnaireInput(data: string, state: QuestionnaireDispa
228
229
  }
229
230
 
230
231
  if (q.multiSelect) {
231
- const onNext = state.currentItem?.kind === "next";
232
- // Space toggles the focused row's checkbox. Ignored on the Next sentinel — Next is
233
- // not a real option and has no checked/unchecked state.
232
+ const focusedKind = state.currentItem?.kind;
233
+ const focusedMeta = focusedKind ? ROW_INTENT_META[focusedKind] : undefined;
234
+ // Space toggles the focused row's checkbox. Suppressed on rows whose META declares
235
+ // `blocksMultiToggle` (the Next sentinel) — Next is not a real option and has no
236
+ // checked/unchecked state.
234
237
  if (data === SPACE_KEY) {
235
- if (onNext) return { kind: "ignore" };
238
+ if (focusedMeta?.blocksMultiToggle) return { kind: "ignore" };
236
239
  return { kind: "toggle", index: state.optionIndex };
237
240
  }
238
241
  if (kb.matches(data, KEYBIND_CONFIRM)) {
239
242
  // Enter on a regular row toggles (matching Space) — committing the question is now
240
- // gated behind explicit focus on the Next row, so Enter on options is a no-cost
241
- // way to flip checkboxes without leaving the keyboard home row.
242
- if (!onNext) return { kind: "toggle", index: state.optionIndex };
243
+ // gated behind explicit focus on a row whose META declares `autoSubmitsInMulti`
244
+ // (the Next sentinel), so Enter on options is a no-cost way to flip checkboxes
245
+ // without leaving the keyboard home row.
246
+ if (!focusedMeta?.autoSubmitsInMulti) return { kind: "toggle", index: state.optionIndex };
243
247
  // Enter on Next: carry autoAdvanceTab so the host can advance to the next tab in
244
248
  // multi-question mode, OR submit the dialog in single-question mode
245
249
  // (autoAdvanceTab === undefined when !isMulti). Without this, a single multi-select
@@ -1,22 +1,29 @@
1
1
  import { getMarkdownTheme, type Theme } from "@mariozechner/pi-coding-agent";
2
2
  import { getKeybindings, Input } from "@mariozechner/pi-tui";
3
+ import { type QuestionData, type QuestionnaireResult, type QuestionParams, SENTINEL_LABELS } from "../tool/types.js";
4
+ import { ChatRowView } from "../view/components/chat-row-view.js";
5
+ import { MultiSelectOptions } from "../view/components/multi-select-options.js";
6
+ import { OptionListView } from "../view/components/option-list-view.js";
7
+ import { PreviewBlockRenderer } from "../view/components/preview/preview-block-renderer.js";
8
+ import { PreviewPane } from "../view/components/preview/preview-pane.js";
9
+ import { SubmitPicker } from "../view/components/submit-picker.js";
10
+ import { TabBar } from "../view/components/tab-bar.js";
11
+ import type { WrappingSelectItem, WrappingSelectTheme } from "../view/components/wrapping-select.js";
12
+ import { buildDialog, type DialogComponent } from "../view/dialog-builder.js";
13
+ import { QuestionnaireViewAdapter } from "../view/view-adapter.js";
3
14
  import { type ApplyContext, applyAction, type Effect } from "./apply-action.js";
4
- import { buildDialog, type DialogComponent } from "./dialog-builder.js";
5
15
  import { handleQuestionnaireInput, type QuestionnaireAction } from "./dispatch.js";
6
- import { MultiSelectOptions } from "./multi-select-options.js";
7
- import { OptionListView } from "./option-list-view.js";
8
- import { PreviewBlockRenderer } from "./preview-block-renderer.js";
9
- import { PreviewPane } from "./preview-pane.js";
10
16
  import {
17
+ chatNumberingFor,
11
18
  computeFocusedOptionHasPreview,
12
19
  type QuestionnaireDispatchSnapshot,
13
20
  type QuestionnaireState,
21
+ selectActivePreviewPaneIndex,
22
+ selectActiveView,
23
+ selectMultiSelectProps,
24
+ selectSubmitPickerProps,
25
+ selectTabBarProps,
14
26
  } from "./questionnaire-state.js";
15
- import { SubmitPicker } from "./submit-picker.js";
16
- import { TabBar } from "./tab-bar.js";
17
- import { type QuestionData, type QuestionnaireResult, type QuestionParams, SENTINEL_LABELS } from "./types.js";
18
- import { QuestionnaireViewAdapter } from "./view-adapter.js";
19
- import { WrappingSelect, type WrappingSelectItem, type WrappingSelectTheme } from "./wrapping-select.js";
20
27
 
21
28
  const BACKSPACE_CHARS = new Set(["\x7f", "\b"]);
22
29
  const ESC_SEQUENCE_PREFIX = "\x1b";
@@ -67,7 +74,7 @@ export class QuestionnaireSession {
67
74
  private readonly multiSelectOptionsByTab: ReadonlyArray<MultiSelectOptions | undefined>;
68
75
  private readonly submitPicker: SubmitPicker | undefined;
69
76
  private readonly tabBar: TabBar | undefined;
70
- private readonly chatList: WrappingSelect;
77
+ private readonly chatRow: ChatRowView;
71
78
  private readonly notesInput: Input;
72
79
  private readonly dialog: DialogComponent;
73
80
  private readonly viewAdapter: QuestionnaireViewAdapter;
@@ -92,7 +99,14 @@ export class QuestionnaireSession {
92
99
  description: (t) => config.theme.fg("muted", t),
93
100
  scrollInfo: (t) => config.theme.fg("dim", t),
94
101
  };
95
- this.chatList = new WrappingSelect([{ kind: "chat", label: SENTINEL_LABELS.chat }], 1, selectTheme);
102
+ this.chatRow = new ChatRowView({
103
+ item: { kind: "chat", label: SENTINEL_LABELS.chat },
104
+ theme: selectTheme,
105
+ initialProps: {
106
+ focused: false,
107
+ numbering: chatNumberingFor(this.itemsByTab[0] ?? []),
108
+ },
109
+ });
96
110
  this.notesInput = new Input();
97
111
 
98
112
  this.optionListViewsByTab = this.itemsByTab.map((items) => new OptionListView({ items, theme: selectTheme }));
@@ -111,34 +125,37 @@ export class QuestionnaireSession {
111
125
  getTerminalWidth,
112
126
  optionListView: this.optionListViewsByTab[i]!,
113
127
  previewBlock,
128
+ initialProps: { notesVisible: false, selectedIndex: 0, focused: false },
114
129
  });
115
130
  });
116
131
 
117
132
  const initialSnap = this.snapshot();
133
+ const initialActiveView = selectActiveView(initialSnap, this.questions.length);
118
134
  this.multiSelectOptionsByTab = this.questions.map((q) =>
119
- q.multiSelect ? new MultiSelectOptions(config.theme, q, initialSnap) : undefined,
135
+ q.multiSelect
136
+ ? new MultiSelectOptions(config.theme, q, selectMultiSelectProps(initialSnap, q, initialActiveView))
137
+ : undefined,
120
138
  );
121
- this.submitPicker = this.isMulti ? new SubmitPicker(config.theme, initialSnap) : undefined;
122
- this.tabBar = this.isMulti
123
- ? new TabBar(
124
- {
125
- questions: this.questions,
126
- answers: new Map(),
127
- activeTabIndex: 0,
128
- totalTabs: this.questions.length + 1,
129
- },
139
+ this.submitPicker = this.isMulti
140
+ ? new SubmitPicker(
130
141
  config.theme,
142
+ selectSubmitPickerProps(initialSnap, this.questions.length, initialActiveView),
131
143
  )
132
144
  : undefined;
145
+ this.tabBar = this.isMulti ? new TabBar(selectTabBarProps(initialSnap, this.questions), config.theme) : undefined;
133
146
 
134
147
  this.dialog = buildDialog({
135
148
  theme: config.theme,
136
149
  questions: this.questions,
137
- state: initialSnap,
138
- previewPane: this.previewPanes[0]!,
150
+ initialProps: {
151
+ state: initialSnap,
152
+ activePreviewPane:
153
+ this.previewPanes[selectActivePreviewPaneIndex(this.state.currentTab, this.questions.length)] ??
154
+ this.previewPanes[0]!,
155
+ },
139
156
  tabBar: this.tabBar,
140
157
  notesInput: this.notesInput,
141
- chatList: this.chatList,
158
+ chatRow: this.chatRow,
142
159
  isMulti: this.isMulti,
143
160
  multiSelectOptionsByTab: this.multiSelectOptionsByTab,
144
161
  submitPicker: this.submitPicker,
@@ -152,7 +169,7 @@ export class QuestionnaireSession {
152
169
  itemsByTab: this.itemsByTab,
153
170
  optionListViewsByTab: this.optionListViewsByTab,
154
171
  previewPanes: this.previewPanes,
155
- chatList: this.chatList,
172
+ chatRow: this.chatRow,
156
173
  multiSelectOptionsByTab: this.multiSelectOptionsByTab,
157
174
  submitPicker: this.submitPicker,
158
175
  tabBar: this.tabBar,
@@ -214,9 +231,6 @@ export class QuestionnaireSession {
214
231
  case "set_notes_focused":
215
232
  this.notesInput.focused = effect.focused;
216
233
  return;
217
- case "set_active_preview_pane":
218
- this.viewAdapter.setActivePreviewPane(effect.paneIndex);
219
- return;
220
234
  case "done":
221
235
  this.done(effect.result);
222
236
  return;
@@ -0,0 +1,321 @@
1
+ import type { QuestionAnswer, QuestionData } from "../tool/types.js";
2
+ import type { ChatRowViewProps } from "../view/components/chat-row-view.js";
3
+ import type { MultiSelectOptionsProps } from "../view/components/multi-select-options.js";
4
+ import type { OptionListViewProps } from "../view/components/option-list-view.js";
5
+ import type { PreviewPaneProps } from "../view/components/preview/preview-pane.js";
6
+ import type { SubmitPickerProps } from "../view/components/submit-picker.js";
7
+ import type { TabBarProps } from "../view/components/tab-bar.js";
8
+ import type { WrappingSelectItem } from "../view/components/wrapping-select.js";
9
+ import type { ActiveView } from "../view/stateful-view.js";
10
+ import { ROW_INTENT_META } from "./row-intent.js";
11
+
12
+ /**
13
+ * Canonical state for the questionnaire dialog. Single source of truth — both the
14
+ * dispatcher (`handleQuestionnaireInput`) and the view layer (`buildDialog`,
15
+ * `MultiSelectOptions.setState`, `SubmitPicker.setState`) read this same shape.
16
+ */
17
+ export interface QuestionnaireState {
18
+ currentTab: number;
19
+ optionIndex: number;
20
+ inputMode: boolean;
21
+ notesVisible: boolean;
22
+ chatFocused: boolean;
23
+ answers: ReadonlyMap<number, QuestionAnswer>;
24
+ multiSelectChecked: ReadonlySet<number>;
25
+ /**
26
+ * Pre-answer notes side-band, keyed by tab index. OPTIONAL on the canonical type to
27
+ * preserve existing test-factory shapes (`dispatch.test.ts:43-63`,
28
+ * `multi-select-options.test.ts:11-23`, `submit-picker.test.ts:13-25`); the reducer
29
+ * treats `undefined` as an empty map. Decoupled from `answers` so adding notes does NOT
30
+ * make `answers.has(currentTab)` true (otherwise Submit-tab missing-check + `allAnswered()`
31
+ * would falsely report the question as answered). Merged into the answer at confirm time.
32
+ */
33
+ notesByTab?: ReadonlyMap<number, string>;
34
+ /**
35
+ * True iff the currently-focused option carries a non-empty `preview` string.
36
+ * Computed via `computeFocusedOptionHasPreview` below. Stored on state because it
37
+ * gates the `notes_enter` action and the "n to add notes" hint chip.
38
+ */
39
+ focusedOptionHasPreview: boolean;
40
+ /**
41
+ * Focused row in the Submit-tab picker (0 = Submit answers, 1 = Cancel). Default 0;
42
+ * reset on every tab switch.
43
+ */
44
+ submitChoiceIndex: number;
45
+ }
46
+
47
+ /**
48
+ * Per-tick context the dispatcher needs alongside the canonical state. Lives separately
49
+ * from `QuestionnaireState` because these fields don't belong on the view-side state
50
+ * (the view's `setState` consumers should not see `keybindings` or `inputBuffer`).
51
+ */
52
+ export interface QuestionnaireRuntime {
53
+ keybindings: { matches(data: string, name: string): boolean };
54
+ inputBuffer: string;
55
+ questions: readonly QuestionData[];
56
+ isMulti: boolean;
57
+ currentItem: WrappingSelectItem | undefined;
58
+ items: readonly WrappingSelectItem[];
59
+ }
60
+
61
+ /**
62
+ * Combined snapshot read by the dispatcher. The view receives the same object —
63
+ * structural typing accepts the superset wherever a `QuestionnaireState` is expected
64
+ * (covariance), so a single `snapshot()` call serves both consumers.
65
+ */
66
+ export type QuestionnaireDispatchSnapshot = QuestionnaireState & QuestionnaireRuntime;
67
+
68
+ /**
69
+ * Pure derivation: does the option focused by `(currentTab, optionIndex)` carry a
70
+ * non-empty `preview` string? Mode gates (chat focus, notes mode, multiSelect) layer
71
+ * on top via dispatch branches; this predicate is intentionally mode-agnostic.
72
+ */
73
+ export function computeFocusedOptionHasPreview(
74
+ questions: readonly QuestionData[],
75
+ currentTab: number,
76
+ optionIndex: number,
77
+ ): boolean {
78
+ const q = questions[currentTab];
79
+ if (!q) return false;
80
+ const opt = q.options[optionIndex];
81
+ return !!opt && typeof opt.preview === "string" && opt.preview.length > 0;
82
+ }
83
+
84
+ /**
85
+ * Numbering for the chat row's WrappingSelect, computed from the active tab's items.
86
+ *
87
+ * The chat row lives in its own one-item WrappingSelect; the host calls this on every tab
88
+ * switch / selection update to keep the chat row's `N. ` label continuous with the visible
89
+ * numbered rows of the active tab. The shape `{ offset, total }` mirrors `WrappingSelect.setNumbering(numberStartOffset, totalItemsForNumbering)` directly.
90
+ */
91
+ export function chatNumberingFor(items: readonly WrappingSelectItem[]): {
92
+ offset: number;
93
+ total: number;
94
+ } {
95
+ // Count only the visible-numbered rows. The Next sentinel renders without a number
96
+ // (see MultiSelectOptions), so it must NOT advance the chat row's number — otherwise
97
+ // chat reads as "6." next to options labeled 1-4. Sourced from `ROW_INTENT_META[kind].numbered`
98
+ // so adding a new non-numbered kind is a single META edit.
99
+ const count = items.filter((i) => ROW_INTENT_META[i.kind].numbered).length;
100
+ return { offset: count, total: count + 1 };
101
+ }
102
+
103
+ /**
104
+ * Which row in the active tab should be marked as "previously confirmed"? Drives the
105
+ * `WrappingSelect` confirmed-row indicator (label + ` ✔`) when the user navigates back
106
+ * to a question they already answered. Returns `undefined` when no marker should be drawn —
107
+ * multi-select handles its own `[✔]` boxes via `multiSelectChecked`, `kind: "chat"` ends the
108
+ * dialog so the row can never be re-entered, and a missing/non-matching answer (defensive)
109
+ * silently skips the marker.
110
+ */
111
+ export function selectConfirmedIndicator(
112
+ questions: readonly QuestionData[],
113
+ currentTab: number,
114
+ answers: ReadonlyMap<number, QuestionAnswer>,
115
+ items: readonly WrappingSelectItem[],
116
+ ): { index: number; labelOverride?: string } | undefined {
117
+ const q = questions[currentTab];
118
+ if (!q || q.multiSelect === true) return undefined;
119
+ const prior = answers.get(currentTab);
120
+ if (!prior || prior.kind === "chat") return undefined;
121
+ if (prior.kind === "custom") {
122
+ const otherIndex = items.findIndex((it) => it.kind === "other");
123
+ if (otherIndex < 0) return undefined;
124
+ return { index: otherIndex, labelOverride: prior.answer ?? "" };
125
+ }
126
+ if (prior.kind !== "option" || typeof prior.answer !== "string") return undefined;
127
+ const index = items.findIndex((it) => it.kind === "option" && it.label === prior.answer);
128
+ if (index < 0) return undefined;
129
+ return { index };
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
+ * Discriminated focus selector — single source of truth for "which view
157
+ * owns focus this tick?" Priority order is load-bearing: matches the
158
+ * dispatcher cascade (`dispatch.ts:151-178`) and the reducer's defensive
159
+ * clears (`apply-action.ts:104-126`).
160
+ *
161
+ * - `notes` — notes overlay is visible (highest priority — even on Submit tab).
162
+ * - `submit` — currently on the Submit Tab (multi-question only).
163
+ * - `chat` — chat row owns focus.
164
+ * - `options` — default; the active tab's option list owns focus.
165
+ *
166
+ * Per-component `focused: boolean` flags are derived from one equality
167
+ * check against this discriminant, replacing the four parallel reads at
168
+ * `view-adapter.ts:84,104,106,115`.
169
+ */
170
+ export function selectActiveView(
171
+ state: { notesVisible: boolean; chatFocused: boolean; currentTab: number },
172
+ totalQuestions: number,
173
+ ): ActiveView {
174
+ if (state.notesVisible) return "notes";
175
+ if (state.currentTab === totalQuestions) return "submit";
176
+ if (state.chatFocused) return "chat";
177
+ return "options";
178
+ }
179
+
180
+ /**
181
+ * Per-tick projection for a `MultiSelectOptions` instance. Pre-computes
182
+ * `checked` and `active` per row + the `nextActive` flag so the component's
183
+ * render body is pure styling.
184
+ *
185
+ * Broadcast-safe: every multi-select tab's MSO receives a projection per
186
+ * tick (preserving `view-adapter.ts:108-112` pattern), but only the active
187
+ * tab actually renders its body via `QuestionTabStrategy.bodyComponent`.
188
+ * Non-active MSO instances see `focused === false` because activeView is
189
+ * gated on `state.notesVisible` / `state.chatFocused` / Submit-tab — none
190
+ * of which are true while in options mode on the active tab.
191
+ */
192
+ export function selectMultiSelectProps(
193
+ state: QuestionnaireState,
194
+ question: QuestionData,
195
+ activeView: ActiveView,
196
+ ): MultiSelectOptionsProps {
197
+ const focused = activeView === "options";
198
+ const rows: { checked: boolean; active: boolean }[] = [];
199
+ for (let i = 0; i < question.options.length; i++) {
200
+ rows.push({
201
+ checked: state.multiSelectChecked.has(i),
202
+ active: focused && i === state.optionIndex,
203
+ });
204
+ }
205
+ const nextActive = focused && state.optionIndex === question.options.length;
206
+ return { rows, nextActive };
207
+ }
208
+
209
+ /**
210
+ * Per-tick projection for the active tab's `OptionListView`. Reuses
211
+ * `selectConfirmedIndicator` (no duplication) and adds the focus
212
+ * derivation. Called only for the active pane index — non-active OLV
213
+ * instances retain their last props until tab-switch (current behavior
214
+ * preserved per research artifact: only the active tab's OLV is rendered
215
+ * by `QuestionTabStrategy.bodyComponent`).
216
+ */
217
+ export function selectOptionListProps(
218
+ state: QuestionnaireState,
219
+ items: readonly WrappingSelectItem[],
220
+ questions: readonly QuestionData[],
221
+ activeView: ActiveView,
222
+ ): OptionListViewProps {
223
+ const focused = activeView === "options";
224
+ const confirmed = selectConfirmedIndicator(questions, state.currentTab, state.answers, items);
225
+ return {
226
+ selectedIndex: state.optionIndex,
227
+ focused,
228
+ ...(confirmed ? { confirmed } : {}),
229
+ };
230
+ }
231
+
232
+ /**
233
+ * Per-tick projection for the SubmitPicker. Two rows fixed (Submit /
234
+ * Cancel); only `active` per row varies. Focus derives from the
235
+ * `activeView === "submit"` discriminant.
236
+ */
237
+ export function selectSubmitPickerProps(
238
+ state: QuestionnaireState,
239
+ totalQuestions: number,
240
+ activeView: ActiveView,
241
+ ): SubmitPickerProps {
242
+ const focused = activeView === "submit";
243
+ void totalQuestions; // reserved arg for symmetry with other selectors
244
+ return {
245
+ rows: [
246
+ { active: focused && state.submitChoiceIndex === 0 },
247
+ { active: focused && state.submitChoiceIndex === 1 },
248
+ ],
249
+ };
250
+ }
251
+
252
+ /**
253
+ * Per-tick projection for `PreviewPane`. Eliminates the sibling-coupling
254
+ * where `PreviewPane` formerly read `optionListView.getSelectedIndex()` /
255
+ * `isFocused()` live during render. Both `OptionListView` and
256
+ * `PreviewPane.setProps` now derive `selectedIndex` and `focused` from the
257
+ * same canonical state per tick — the cross-component live read is gone.
258
+ *
259
+ * Called only for the active pane (per current adapter behavior — non-active
260
+ * panes never render).
261
+ */
262
+ export function selectPreviewPaneProps(state: QuestionnaireState, activeView: ActiveView): PreviewPaneProps {
263
+ return {
264
+ notesVisible: state.notesVisible,
265
+ selectedIndex: state.optionIndex,
266
+ focused: activeView === "options",
267
+ };
268
+ }
269
+
270
+ /**
271
+ * Per-tick projection for the TabBar. Hoists all per-render derivations
272
+ * (`allAnswered`, `answered`, `isActive`, `submitActive`) out of `tab-bar.ts`
273
+ * into the selector. Replaces the inline `+ 1` magic at `view-adapter.ts:127`
274
+ * — the Submit slot is now an explicit `submit` field, not a hidden
275
+ * `totalTabs` index.
276
+ *
277
+ * `Q{n}` fallback label is computed here once per tab; `header` reads
278
+ * directly from question data.
279
+ */
280
+ export function selectTabBarProps(
281
+ state: QuestionnaireState,
282
+ questions: ReadonlyArray<{ header?: string; question: string }>,
283
+ ): TabBarProps {
284
+ const tabs = questions.map((q, i) => ({
285
+ label: q.header && q.header.length > 0 ? q.header : `Q${i + 1}`,
286
+ answered: state.answers.has(i),
287
+ active: i === state.currentTab,
288
+ }));
289
+ return {
290
+ tabs,
291
+ submit: {
292
+ active: state.currentTab === questions.length,
293
+ allAnswered: state.answers.size === questions.length && questions.length > 0,
294
+ },
295
+ };
296
+ }
297
+
298
+ /**
299
+ * Per-tick projection for `ChatRowView`. Combines focus discriminant with
300
+ * the numbering derivation (`chatNumberingFor` over the active tab's
301
+ * items). Replaces the two adapter-side calls
302
+ * (`chatList.setFocused(state.chatFocused)` at `view-adapter.ts:106` +
303
+ * `chatList.setNumbering(...)` at `:120`) with one selector + one setProps.
304
+ *
305
+ * `activeView === "chat"` is observably equivalent to `state.chatFocused`
306
+ * because the dispatcher cascade (`dispatch.ts:151-178`) and reducer's
307
+ * defensive clears (`apply-action.ts:104-126`) ensure `chatFocused` and
308
+ * `notesVisible`/Submit-tab cannot be true simultaneously.
309
+ */
310
+ export function selectChatRowProps(
311
+ state: QuestionnaireState,
312
+ itemsByTab: ReadonlyArray<readonly WrappingSelectItem[]>,
313
+ totalQuestions: number,
314
+ activeView: ActiveView,
315
+ ): ChatRowViewProps {
316
+ const activeItems = selectActiveTabItems(itemsByTab, state.currentTab, totalQuestions);
317
+ return {
318
+ focused: activeView === "chat",
319
+ numbering: chatNumberingFor(activeItems),
320
+ };
321
+ }