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

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.6",
3
+ "version": "1.0.8",
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",
@@ -35,6 +35,7 @@
35
35
  "state/key-router.ts",
36
36
  "state/questionnaire-session.ts",
37
37
  "state/row-intent.ts",
38
+ "state/selectors/contract.ts",
38
39
  "state/selectors/derivations.ts",
39
40
  "state/selectors/focus.ts",
40
41
  "state/selectors/projections.ts",
@@ -45,6 +46,7 @@
45
46
  "tool/types.ts",
46
47
  "tool/validate-questionnaire.ts",
47
48
  "view/body-residual-spacer.ts",
49
+ "view/component-binding.ts",
48
50
  "view/components/chat-row-view.ts",
49
51
  "view/components/multi-select-view.ts",
50
52
  "view/components/option-list-view.ts",
@@ -1,6 +1,12 @@
1
1
  import { getMarkdownTheme, type Theme } from "@mariozechner/pi-coding-agent";
2
2
  import { Input } from "@mariozechner/pi-tui";
3
3
  import { type QuestionData, SENTINEL_LABELS } from "../tool/types.js";
4
+ import {
5
+ type BoundGlobalBinding,
6
+ type BoundPerTabBinding,
7
+ globalBinding,
8
+ perTabBinding,
9
+ } from "../view/component-binding.js";
4
10
  import { ChatRowView } from "../view/components/chat-row-view.js";
5
11
  import { MultiSelectView } from "../view/components/multi-select-view.js";
6
12
  import { OptionListView } from "../view/components/option-list-view.js";
@@ -9,13 +15,21 @@ import { PreviewPane } from "../view/components/preview/preview-pane.js";
9
15
  import { SubmitPicker } from "../view/components/submit-picker.js";
10
16
  import { TabBar } from "../view/components/tab-bar.js";
11
17
  import type { WrappingSelectItem, WrappingSelectTheme } from "../view/components/wrapping-select.js";
12
- import { buildDialog } from "../view/dialog-builder.js";
18
+ import { DialogView } from "../view/dialog-builder.js";
13
19
  import { QuestionnairePropsAdapter } from "../view/props-adapter.js";
14
20
  import type { TabComponents } from "../view/tab-components.js";
15
21
  import type { InputBuffer } from "./input-buffer.js";
16
- import { chatNumberingFor, selectActivePreviewPaneIndex } from "./selectors/derivations.js";
17
- import { selectActiveView } from "./selectors/focus.js";
18
- import { selectMultiSelectProps, selectSubmitPickerProps, selectTabBarProps } from "./selectors/projections.js";
22
+ import type { PerTabSelector } from "./selectors/contract.js";
23
+ import { selectActivePreviewPaneIndex } from "./selectors/derivations.js";
24
+ import {
25
+ selectChatRowProps,
26
+ selectDialogProps,
27
+ selectMultiSelectProps,
28
+ selectOptionListProps,
29
+ selectPreviewPaneProps,
30
+ selectSubmitPickerProps,
31
+ selectTabBarProps,
32
+ } from "./selectors/projections.js";
19
33
  import type { QuestionnaireState } from "./state.js";
20
34
 
21
35
  export interface QuestionnaireBuildConfig {
@@ -39,7 +53,9 @@ export interface QuestionnaireBuilt {
39
53
  /**
40
54
  * Pure factory: assembles every TUI component, the props adapter, and a
41
55
  * lifecycle handle. Session-state dependencies arrive via `getCurrentTab` and
42
- * the `inputBuffer` cell.
56
+ * the `inputBuffer` cell. Initial paint is delegated to
57
+ * `adapter.apply(initialState)` (called by the session at construction-end);
58
+ * no selector is invoked here.
43
59
  */
44
60
  export function buildQuestionnaire(config: QuestionnaireBuildConfig): QuestionnaireBuilt {
45
61
  const { tui, theme, questions, itemsByTab, isMulti, initialState, inputBuffer, getCurrentTab } = config;
@@ -54,16 +70,16 @@ export function buildQuestionnaire(config: QuestionnaireBuildConfig): Questionna
54
70
  const chatRow = new ChatRowView({
55
71
  item: { kind: "chat", label: SENTINEL_LABELS.chat },
56
72
  theme: selectTheme,
57
- initialProps: {
58
- focused: false,
59
- numbering: chatNumberingFor(itemsByTab[0] ?? []),
60
- },
61
73
  });
62
74
  const notesInput = new Input();
63
75
 
64
76
  const markdownTheme = getMarkdownTheme();
65
77
  const getTerminalWidth = () => tui.terminal.columns;
66
- const initialActiveView = selectActiveView(initialState, totalQuestions);
78
+
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)[] = [];
67
83
 
68
84
  const tabsByIndex: ReadonlyArray<TabComponents> = questions.map((q, i) => {
69
85
  const optionList = new OptionListView({ items: itemsByTab[i] ?? [], theme: selectTheme });
@@ -73,27 +89,25 @@ export function buildQuestionnaire(config: QuestionnaireBuildConfig): Questionna
73
89
  getTerminalWidth,
74
90
  optionListView: optionList,
75
91
  previewBlock,
76
- initialProps: { notesVisible: false, selectedIndex: 0, focused: false },
77
92
  });
78
- const multiSelect = q.multiSelect
79
- ? new MultiSelectView(theme, q, selectMultiSelectProps(initialState, q, initialActiveView))
80
- : undefined;
93
+ const multiSelect = q.multiSelect ? new MultiSelectView(theme, q) : undefined;
94
+
95
+ previewPanesByTab.push(preview);
96
+ multiSelectViewsByTab.push(multiSelect);
97
+
81
98
  return { optionList, preview, multiSelect };
82
99
  });
83
100
 
84
- const submitPicker = isMulti
85
- ? new SubmitPicker(theme, selectSubmitPickerProps(initialState, totalQuestions, initialActiveView))
86
- : undefined;
87
- const tabBar = isMulti ? new TabBar(selectTabBarProps(initialState, questions), theme) : undefined;
101
+ const submitPicker = isMulti ? new SubmitPicker(theme) : undefined;
102
+ const tabBar = isMulti ? new TabBar(theme) : undefined;
88
103
 
89
104
  const computeGlobalContentHeight = (width: number): number => {
90
105
  let max = 0;
91
106
  for (let i = 0; i < questions.length; i++) {
92
107
  const q = questions[i];
93
- const tab = tabsByIndex[i];
94
108
  const h = q?.multiSelect
95
- ? (tab?.multiSelect?.naturalHeight(width) ?? 0)
96
- : (tab?.preview.maxNaturalHeight(width) ?? 0);
109
+ ? (multiSelectViewsByTab[i]?.naturalHeight(width) ?? 0)
110
+ : (previewPanesByTab[i]?.maxNaturalHeight(width) ?? 0);
97
111
  if (h > max) max = h;
98
112
  }
99
113
  return Math.max(1, max);
@@ -101,47 +115,76 @@ export function buildQuestionnaire(config: QuestionnaireBuildConfig): Questionna
101
115
  const computeCurrentContentHeight = (width: number): number => {
102
116
  const idx = Math.min(getCurrentTab(), questions.length - 1);
103
117
  const q = questions[idx];
104
- const tab = tabsByIndex[idx];
105
- if (!q || !tab) return 0;
106
- const h = q.multiSelect ? (tab.multiSelect?.naturalHeight(width) ?? 0) : tab.preview.naturalHeight(width);
118
+ if (!q) return 0;
119
+ const h = q.multiSelect
120
+ ? (multiSelectViewsByTab[idx]?.naturalHeight(width) ?? 0)
121
+ : (previewPanesByTab[idx]?.naturalHeight(width) ?? 0);
107
122
  return Math.max(0, h);
108
123
  };
109
124
 
110
- const dialog = buildDialog({
111
- theme,
112
- questions,
113
- initialProps: {
114
- state: initialState,
115
- activePreviewPane:
116
- tabsByIndex[selectActivePreviewPaneIndex(initialState.currentTab, totalQuestions)]?.preview ??
117
- tabsByIndex[0]!.preview,
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,
118
140
  },
119
- tabBar,
120
- notesInput,
121
- chatRow,
122
- isMulti,
123
- tabsByIndex,
124
- submitPicker,
125
- getBodyHeight: computeGlobalContentHeight,
126
- getCurrentBodyHeight: computeCurrentContentHeight,
127
- });
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
+ };
155
+
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
+ ];
128
172
 
129
173
  const adapter = new QuestionnairePropsAdapter({
130
174
  tui,
131
175
  questions,
132
176
  itemsByTab,
133
177
  tabsByIndex,
134
- chatRow,
135
- submitPicker,
136
- tabBar,
137
- dialog,
138
178
  inputBuffer,
179
+ globalBindings,
180
+ perTabBindings,
181
+ extraInvalidatables: [notesInput],
139
182
  });
140
183
 
141
184
  return {
142
185
  adapter,
143
186
  notesInput,
144
187
  render: (w) => dialog.render(w),
145
- invalidate: () => dialog.invalidate(),
188
+ invalidate: () => adapter.invalidate(),
146
189
  };
147
190
  }
@@ -0,0 +1,23 @@
1
+ import type { QuestionData } from "../../tool/types.js";
2
+ import type { PreviewPaneProps } from "../../view/components/preview/preview-pane.js";
3
+ import type { WrappingSelectItem } from "../../view/components/wrapping-select.js";
4
+ import type { ActiveView, StatefulView } from "../../view/stateful-view.js";
5
+ import type { TabComponents } from "../../view/tab-components.js";
6
+ import type { QuestionnaireState } from "../state.js";
7
+
8
+ export interface BindingContext {
9
+ readonly questions: readonly QuestionData[];
10
+ readonly itemsByTab: ReadonlyArray<readonly WrappingSelectItem[]>;
11
+ readonly totalQuestions: number;
12
+ readonly activeView: ActiveView;
13
+ readonly inputBuffer: string;
14
+ readonly activePreviewPane: StatefulView<PreviewPaneProps>;
15
+ }
16
+
17
+ export interface PerTabBindingContext extends BindingContext {
18
+ readonly tab: TabComponents;
19
+ readonly i: number;
20
+ }
21
+
22
+ export type GlobalSelector<P> = (state: QuestionnaireState, ctx: BindingContext) => P;
23
+ export type PerTabSelector<P> = (state: QuestionnaireState, ctx: PerTabBindingContext) => P;
@@ -1,33 +1,18 @@
1
- import type { QuestionData } from "../../tool/types.js";
1
+ import { SENTINEL_LABELS } from "../../tool/types.js";
2
2
  import type { ChatRowViewProps } from "../../view/components/chat-row-view.js";
3
- import type { MultiSelectViewProps } from "../../view/components/multi-select-view.js";
3
+ import { MULTI_SUBMIT_LABEL, type MultiSelectViewProps } from "../../view/components/multi-select-view.js";
4
4
  import type { OptionListViewProps } from "../../view/components/option-list-view.js";
5
5
  import type { PreviewPaneProps } from "../../view/components/preview/preview-pane.js";
6
6
  import type { SubmitPickerProps } from "../../view/components/submit-picker.js";
7
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 type { QuestionnaireState } from "../state.js";
8
+ import type { DialogProps } from "../../view/dialog-builder.js";
9
+ import type { GlobalSelector, PerTabSelector } from "./contract.js";
11
10
  import { chatNumberingFor, selectActiveTabItems, selectConfirmedIndicator } from "./derivations.js";
12
11
 
13
- /**
14
- * Per-tick projection for a `MultiSelectView` instance. Pre-computes
15
- * `checked` and `active` per row + the `nextActive` flag so the component's
16
- * render body is pure styling.
17
- *
18
- * Broadcast-safe: every multi-select tab's MSO receives a projection per
19
- * tick, but only the active tab actually renders its body via
20
- * `QuestionTabStrategy.bodyComponent`. Non-active MSO instances see
21
- * `focused === false` because activeView is gated on `state.notesVisible` /
22
- * `state.chatFocused` / Submit-tab — none of which are true while in options
23
- * mode on the active tab.
24
- */
25
- export function selectMultiSelectProps(
26
- state: QuestionnaireState,
27
- question: QuestionData,
28
- activeView: ActiveView,
29
- ): MultiSelectViewProps {
30
- const focused = activeView === "options";
12
+ export const selectMultiSelectProps: PerTabSelector<MultiSelectViewProps> = (state, ctx) => {
13
+ const question = ctx.questions[ctx.i];
14
+ if (!question) return { rows: [], nextActive: false, nextLabel: SENTINEL_LABELS.next };
15
+ const focused = ctx.activeView === "options";
31
16
  const rows: { checked: boolean; active: boolean }[] = [];
32
17
  for (let i = 0; i < question.options.length; i++) {
33
18
  rows.push({
@@ -36,78 +21,41 @@ export function selectMultiSelectProps(
36
21
  });
37
22
  }
38
23
  const nextActive = focused && state.optionIndex === question.options.length;
39
- return { rows, nextActive };
40
- }
24
+ const isLastQuestion = ctx.i === ctx.questions.length - 1;
25
+ const nextLabel = isLastQuestion ? MULTI_SUBMIT_LABEL : SENTINEL_LABELS.next;
26
+ return { rows, nextActive, nextLabel };
27
+ };
41
28
 
42
- /**
43
- * Per-tick projection for the active tab's `OptionListView`. Threads the
44
- * runtime-owned `inputBuffer` through to the view so the rendering primitive
45
- * (`WrappingSelect`) sees the value without per-keystroke reducer involvement.
46
- */
47
- export function selectOptionListProps(
48
- state: QuestionnaireState,
49
- items: readonly WrappingSelectItem[],
50
- questions: readonly QuestionData[],
51
- activeView: ActiveView,
52
- inputBuffer: string,
53
- ): OptionListViewProps {
54
- const focused = activeView === "options";
55
- const confirmed = selectConfirmedIndicator(questions, state.currentTab, state.answers, items);
29
+ export const selectOptionListProps: PerTabSelector<OptionListViewProps> = (state, ctx) => {
30
+ const items = ctx.itemsByTab[ctx.i] ?? [];
31
+ const focused = ctx.activeView === "options";
32
+ const confirmed = selectConfirmedIndicator(ctx.questions, state.currentTab, state.answers, items);
56
33
  return {
57
34
  selectedIndex: state.optionIndex,
58
35
  focused,
59
- inputBuffer,
36
+ inputBuffer: ctx.inputBuffer,
60
37
  ...(confirmed ? { confirmed } : {}),
61
38
  };
62
- }
39
+ };
63
40
 
64
- /**
65
- * Per-tick projection for the SubmitPicker. Two rows fixed (Submit /
66
- * Cancel); only `active` per row varies. Focus derives from the
67
- * `activeView === "submit"` discriminant.
68
- */
69
- export function selectSubmitPickerProps(
70
- state: QuestionnaireState,
71
- totalQuestions: number,
72
- activeView: ActiveView,
73
- ): SubmitPickerProps {
74
- const focused = activeView === "submit";
75
- void totalQuestions;
41
+ export const selectSubmitPickerProps: GlobalSelector<SubmitPickerProps> = (state, ctx) => {
42
+ const focused = ctx.activeView === "submit";
76
43
  return {
77
44
  rows: [
78
45
  { active: focused && state.submitChoiceIndex === 0 },
79
46
  { active: focused && state.submitChoiceIndex === 1 },
80
47
  ],
81
48
  };
82
- }
49
+ };
83
50
 
84
- /**
85
- * Per-tick projection for `PreviewPane`. Eliminates the sibling-coupling
86
- * where `PreviewPane` formerly read `optionListView.getSelectedIndex()` /
87
- * `isFocused()` live during render. Both `OptionListView` and
88
- * `PreviewPane.setProps` derive `selectedIndex` and `focused` from the same
89
- * canonical state per tick.
90
- */
91
- export function selectPreviewPaneProps(state: QuestionnaireState, activeView: ActiveView): PreviewPaneProps {
92
- return {
93
- notesVisible: state.notesVisible,
94
- selectedIndex: state.optionIndex,
95
- focused: activeView === "options",
96
- };
97
- }
51
+ export const selectPreviewPaneProps: PerTabSelector<PreviewPaneProps> = (state, ctx) => ({
52
+ notesVisible: state.notesVisible,
53
+ selectedIndex: state.optionIndex,
54
+ focused: ctx.activeView === "options",
55
+ });
98
56
 
99
- /**
100
- * Per-tick projection for the TabBar. Hoists all per-render derivations
101
- * (`allAnswered`, `answered`, `isActive`, `submitActive`) out of `tab-bar.ts`
102
- * into the selector. The Submit slot is an explicit `submit` field, not a
103
- * hidden `totalTabs` index. `Q{n}` fallback label is computed here once per
104
- * tab; `header` reads directly from question data.
105
- */
106
- export function selectTabBarProps(
107
- state: QuestionnaireState,
108
- questions: ReadonlyArray<{ header?: string; question: string }>,
109
- ): TabBarProps {
110
- const tabs = questions.map((q, i) => ({
57
+ export const selectTabBarProps: GlobalSelector<TabBarProps> = (state, ctx) => {
58
+ const tabs = ctx.questions.map((q, i) => ({
111
59
  label: q.header && q.header.length > 0 ? q.header : `Q${i + 1}`,
112
60
  answered: state.answers.has(i),
113
61
  active: i === state.currentTab,
@@ -115,29 +63,21 @@ export function selectTabBarProps(
115
63
  return {
116
64
  tabs,
117
65
  submit: {
118
- active: state.currentTab === questions.length,
119
- allAnswered: state.answers.size === questions.length && questions.length > 0,
66
+ active: state.currentTab === ctx.questions.length,
67
+ allAnswered: state.answers.size === ctx.questions.length && ctx.questions.length > 0,
120
68
  },
121
69
  };
122
- }
70
+ };
123
71
 
124
- /**
125
- * Per-tick projection for `ChatRowView`. Combines focus discriminant with
126
- * the numbering derivation (`chatNumberingFor` over the active tab's
127
- * items). `activeView === "chat"` is observably equivalent to
128
- * `state.chatFocused` because the dispatcher cascade and reducer's defensive
129
- * clears ensure `chatFocused` and `notesVisible`/Submit-tab cannot be true
130
- * simultaneously.
131
- */
132
- export function selectChatRowProps(
133
- state: QuestionnaireState,
134
- itemsByTab: ReadonlyArray<readonly WrappingSelectItem[]>,
135
- totalQuestions: number,
136
- activeView: ActiveView,
137
- ): ChatRowViewProps {
138
- const activeItems = selectActiveTabItems(itemsByTab, state.currentTab, totalQuestions);
72
+ export const selectChatRowProps: GlobalSelector<ChatRowViewProps> = (state, ctx) => {
73
+ const activeItems = selectActiveTabItems(ctx.itemsByTab, state.currentTab, ctx.totalQuestions);
139
74
  return {
140
- focused: activeView === "chat",
75
+ focused: ctx.activeView === "chat",
141
76
  numbering: chatNumberingFor(activeItems),
142
77
  };
143
- }
78
+ };
79
+
80
+ export const selectDialogProps: GlobalSelector<DialogProps> = (state, ctx) => ({
81
+ state,
82
+ activePreviewPane: ctx.activePreviewPane,
83
+ });
@@ -170,6 +170,7 @@ export function reduce(state: QuestionnaireState, action: QuestionnaireAction, c
170
170
  const answers = new Map(state.answers);
171
171
  answers.set(answer.questionIndex, answer);
172
172
  const next: QuestionnaireState = { ...state, answers };
173
+ if (answer.kind === "chat") return doneFor(next, ctx, false);
173
174
  if (action.autoAdvanceTab !== undefined) return switchTabResult(next, action.autoAdvanceTab, ctx);
174
175
  return doneFor(next, ctx, false);
175
176
  }
@@ -0,0 +1,45 @@
1
+ import type {
2
+ BindingContext,
3
+ GlobalSelector,
4
+ PerTabBindingContext,
5
+ PerTabSelector,
6
+ } from "../state/selectors/contract.js";
7
+ import type { QuestionnaireState } from "../state/state.js";
8
+ import type { StatefulView } from "./stateful-view.js";
9
+ import type { TabComponents } from "./tab-components.js";
10
+
11
+ export interface ComponentBinding<P> {
12
+ readonly component: StatefulView<P>;
13
+ readonly select: GlobalSelector<P>;
14
+ }
15
+
16
+ export interface PerTabBinding<P> {
17
+ readonly resolve: (tab: TabComponents) => StatefulView<P> | undefined;
18
+ readonly select: PerTabSelector<P>;
19
+ readonly predicate?: PerTabSelector<boolean>;
20
+ }
21
+
22
+ export interface BoundGlobalBinding {
23
+ apply(state: QuestionnaireState, ctx: BindingContext): void;
24
+ invalidate(): void;
25
+ }
26
+
27
+ export interface BoundPerTabBinding {
28
+ apply(state: QuestionnaireState, ctx: PerTabBindingContext): void;
29
+ }
30
+
31
+ export function globalBinding<P>(spec: ComponentBinding<P>): BoundGlobalBinding {
32
+ return {
33
+ apply: (state, ctx) => spec.component.setProps(spec.select(state, ctx)),
34
+ invalidate: () => spec.component.invalidate(),
35
+ };
36
+ }
37
+
38
+ export function perTabBinding<P>(spec: PerTabBinding<P>): BoundPerTabBinding {
39
+ return {
40
+ apply: (state, ctx) => {
41
+ if (spec.predicate && !spec.predicate(state, ctx)) return;
42
+ spec.resolve(ctx.tab)?.setProps(spec.select(state, ctx));
43
+ },
44
+ };
45
+ }
@@ -17,7 +17,6 @@ export interface ChatRowViewConfig {
17
17
  /** The single chat sentinel row — `{kind: "chat", label: SENTINEL_LABELS.chat}`. */
18
18
  item: WrappingSelectItem;
19
19
  theme: WrappingSelectTheme;
20
- initialProps: ChatRowViewProps;
21
20
  }
22
21
 
23
22
  /**
@@ -35,10 +34,9 @@ export class ChatRowView implements StatefulView<ChatRowViewProps>, Component {
35
34
 
36
35
  constructor(config: ChatRowViewConfig) {
37
36
  this.select = new WrappingSelect([config.item], 1, config.theme, {
38
- numberStartOffset: config.initialProps.numbering.offset,
39
- totalItemsForNumbering: config.initialProps.numbering.total,
37
+ numberStartOffset: 0,
38
+ totalItemsForNumbering: 1,
40
39
  });
41
- this.select.setFocused(config.initialProps.focused);
42
40
  }
43
41
 
44
42
  setProps(props: ChatRowViewProps): void {
@@ -13,17 +13,12 @@ const BOX_LABEL_GAP = " ";
13
13
  // full prefix column. Wrap width still uses prefixVisibleWidth so naturalHeight matches render.
14
14
  const CONTINUATION_INDENT = " ";
15
15
 
16
- /**
17
- * Per-tick projection of MultiSelectView state. The selector
18
- * (`selectMultiSelectProps`) pre-computes per-row `checked` + `active` so
19
- * `render()` is pure styling — no `state.multiSelectChecked.has(i)` or
20
- * `focused && i === state.optionIndex` predicates inside the render body.
21
- */
16
+ export const MULTI_SUBMIT_LABEL = "Submit";
17
+
22
18
  export interface MultiSelectViewProps {
23
- /** Per-option row state. Length === question.options.length. Order matches question.options[]. */
24
19
  rows: ReadonlyArray<{ checked: boolean; active: boolean }>;
25
- /** True iff the Next sentinel row owns the active pointer. */
26
20
  nextActive: boolean;
21
+ nextLabel: string;
27
22
  }
28
23
 
29
24
  /**
@@ -42,9 +37,8 @@ export class MultiSelectView implements StatefulView<MultiSelectViewProps> {
42
37
  constructor(
43
38
  private readonly theme: Theme,
44
39
  private readonly question: QuestionData,
45
- initialProps: MultiSelectViewProps,
46
40
  ) {
47
- this.props = initialProps;
41
+ this.props = { rows: [], nextActive: false, nextLabel: SENTINEL_LABELS.next };
48
42
  }
49
43
 
50
44
  setProps(props: MultiSelectViewProps): void {
@@ -81,12 +75,10 @@ export class MultiSelectView implements StatefulView<MultiSelectViewProps> {
81
75
  }
82
76
  }
83
77
  }
84
- // Next sentinel — pointer + bare label, no number / no checkbox. Visually distinct from
85
- // option rows so users read it as an action ("commit and advance"), not a togglable row.
86
78
  const nextPointer = this.props.nextActive ? this.theme.fg("accent", ACTIVE_POINTER) : INACTIVE_POINTER;
87
79
  const nextLabel = this.props.nextActive
88
- ? this.theme.fg("accent", this.theme.bold(SENTINEL_LABELS.next))
89
- : SENTINEL_LABELS.next;
80
+ ? this.theme.fg("accent", this.theme.bold(this.props.nextLabel))
81
+ : this.props.nextLabel;
90
82
  lines.push(truncateToWidth(`${nextPointer}${nextLabel}`, width, ""));
91
83
  return lines;
92
84
  }
@@ -56,7 +56,6 @@ export interface PreviewPaneConfig {
56
56
  getTerminalWidth: () => number;
57
57
  optionListView: OptionListView;
58
58
  previewBlock: PreviewBlockRenderer;
59
- initialProps: PreviewPaneProps;
60
59
  }
61
60
 
62
61
  /**
@@ -83,7 +82,7 @@ export class PreviewPane implements StatefulView<PreviewPaneProps>, Component {
83
82
  this.getTerminalWidth = config.getTerminalWidth;
84
83
  this.optionListView = config.optionListView;
85
84
  this.previewBlock = config.previewBlock;
86
- this.props = config.initialProps;
85
+ this.props = { notesVisible: false, selectedIndex: 0, focused: false };
87
86
  }
88
87
 
89
88
  setProps(props: PreviewPaneProps): void {
@@ -33,11 +33,8 @@ export interface SubmitPickerProps {
33
33
  export class SubmitPicker implements StatefulView<SubmitPickerProps> {
34
34
  private props: SubmitPickerProps;
35
35
 
36
- constructor(
37
- private readonly theme: Theme,
38
- initialProps: SubmitPickerProps,
39
- ) {
40
- this.props = initialProps;
36
+ constructor(private readonly theme: Theme) {
37
+ this.props = { rows: [{ active: false }, { active: false }] };
41
38
  }
42
39
 
43
40
  setProps(props: SubmitPickerProps): void {
@@ -19,11 +19,8 @@ export interface TabBarProps {
19
19
  export class TabBar implements StatefulView<TabBarProps> {
20
20
  private props: TabBarProps;
21
21
 
22
- constructor(
23
- initialProps: TabBarProps,
24
- private readonly theme: Theme,
25
- ) {
26
- this.props = initialProps;
22
+ constructor(private readonly theme: Theme) {
23
+ this.props = { tabs: [], submit: { active: false, allAnswered: false } };
27
24
  }
28
25
 
29
26
  setProps(props: TabBarProps): void {
@@ -4,7 +4,7 @@ import type { QuestionnaireState } from "../state/state.js";
4
4
  import type { QuestionData } from "../tool/types.js";
5
5
  import { BodyResidualSpacer } from "./body-residual-spacer.js";
6
6
  import type { ChatRowView } from "./components/chat-row-view.js";
7
- import type { PreviewPane } from "./components/preview/preview-pane.js";
7
+ import type { PreviewPaneProps } from "./components/preview/preview-pane.js";
8
8
  import type { TabBar } from "./components/tab-bar.js";
9
9
  import type { StatefulView } from "./stateful-view.js";
10
10
  import type { TabComponents } from "./tab-components.js";
@@ -29,14 +29,13 @@ export type DialogState = QuestionnaireState;
29
29
  /** Per-tick projection of dialog state. Written by the adapter; read by the strategy thunk. */
30
30
  export interface DialogProps {
31
31
  state: DialogState;
32
- activePreviewPane: PreviewPane;
32
+ activePreviewPane: StatefulView<PreviewPaneProps>;
33
33
  }
34
34
 
35
- /** Construction-time config for `buildDialog`. Frozen after construction. */
35
+ /** Construction-time config for `DialogView`. Frozen after construction. */
36
36
  export interface DialogConfig {
37
37
  theme: Theme;
38
38
  questions: readonly QuestionData[];
39
- initialProps: DialogProps;
40
39
  tabBar: TabBar | undefined;
41
40
  notesInput: Input;
42
41
  chatRow: ChatRowView;
@@ -50,79 +49,86 @@ export interface DialogConfig {
50
49
  getCurrentBodyHeight: (width: number) => number;
51
50
  }
52
51
 
53
- export function buildDialog(config: DialogConfig): StatefulView<DialogProps> {
54
- let liveProps: DialogProps = config.initialProps;
52
+ /**
53
+ * The 7th renderable, promoted from a structural literal to a named class so
54
+ * all view-layer components share one explicit `implements StatefulView<P>`
55
+ * contract. `setProps(DialogProps)` writes the live cell read by the
56
+ * strategy thunk during `render()`. `liveProps.activePreviewPane` is a
57
+ * resolved pane reference threaded by the adapter per tick — the dialog
58
+ * itself does not derive it.
59
+ */
60
+ export class DialogView implements StatefulView<DialogProps> {
61
+ private liveProps: DialogProps;
62
+ private readonly config: DialogConfig;
63
+ private readonly questionStrategy: TabContentStrategy;
64
+ private readonly submitStrategy: TabContentStrategy | undefined;
65
+ private readonly maxFooterRowCount: number;
55
66
 
56
- const questionStrategy: TabContentStrategy = new QuestionTabStrategy({
57
- theme: config.theme,
58
- questions: config.questions,
59
- getPreviewPane: () => liveProps.activePreviewPane,
60
- tabsByIndex: config.tabsByIndex,
61
- notesInput: config.notesInput,
62
- chatRow: config.chatRow,
63
- isMulti: config.isMulti,
64
- getCurrentBodyHeight: config.getCurrentBodyHeight,
65
- });
67
+ constructor(config: DialogConfig, initialProps: DialogProps) {
68
+ this.config = config;
69
+ this.liveProps = initialProps;
70
+ this.questionStrategy = new QuestionTabStrategy({
71
+ theme: config.theme,
72
+ questions: config.questions,
73
+ getPreviewPane: () => this.liveProps.activePreviewPane,
74
+ tabsByIndex: config.tabsByIndex,
75
+ notesInput: config.notesInput,
76
+ chatRow: config.chatRow,
77
+ isMulti: config.isMulti,
78
+ getCurrentBodyHeight: config.getCurrentBodyHeight,
79
+ });
80
+ this.submitStrategy = config.isMulti
81
+ ? new SubmitTabStrategy({
82
+ theme: config.theme,
83
+ questions: config.questions,
84
+ submitPicker: config.submitPicker,
85
+ })
86
+ : undefined;
87
+ this.maxFooterRowCount = Math.max(this.questionStrategy.footerRowCount, this.submitStrategy?.footerRowCount ?? 0);
88
+ }
66
89
 
67
- const submitStrategy: TabContentStrategy | undefined = config.isMulti
68
- ? new SubmitTabStrategy({
69
- theme: config.theme,
70
- questions: config.questions,
71
- submitPicker: config.submitPicker,
72
- })
73
- : undefined;
90
+ setProps(props: DialogProps): void {
91
+ this.liveProps = props;
92
+ }
74
93
 
75
- const maxFooterRowCount = Math.max(questionStrategy.footerRowCount, submitStrategy?.footerRowCount ?? 0);
94
+ handleInput(_data: string): void {}
76
95
 
77
- const component: StatefulView<DialogProps> = {
78
- setProps(props: DialogProps) {
79
- liveProps = props;
80
- },
81
- handleInput() {},
82
- invalidate() {
83
- liveProps.activePreviewPane.invalidate();
84
- config.tabBar?.invalidate();
85
- config.notesInput.invalidate();
86
- config.chatRow.invalidate();
87
- },
88
- render(width: number): string[] {
89
- const onSubmit = config.isMulti && liveProps.state.currentTab === config.questions.length;
90
- const strategy = onSubmit && submitStrategy ? submitStrategy : questionStrategy;
91
- return buildContainerFromStrategy(strategy, config, liveProps, maxFooterRowCount).render(width);
92
- },
93
- };
94
- return component;
95
- }
96
+ // Invalidation is driven by `QuestionnairePropsAdapter.invalidate()`, which
97
+ // owns the full set of renderables (binding registries + extras like
98
+ // `notesInput`). DialogView has no cached layout of its own.
99
+ invalidate(): void {}
100
+
101
+ render(width: number): string[] {
102
+ const onSubmit = this.config.isMulti && this.liveProps.state.currentTab === this.config.questions.length;
103
+ const strategy = onSubmit && this.submitStrategy ? this.submitStrategy : this.questionStrategy;
104
+ return this.buildContainerFromStrategy(strategy).render(width);
105
+ }
96
106
 
97
- function buildContainerFromStrategy(
98
- strategy: TabContentStrategy,
99
- config: DialogConfig,
100
- props: DialogProps,
101
- maxFooterRowCount: number,
102
- ): Container {
103
- const { theme, isMulti, tabBar } = config;
104
- const state = props.state;
105
- const container = new Container();
106
- const border = () => new DynamicBorder((s) => theme.fg("accent", s));
107
+ private buildContainerFromStrategy(strategy: TabContentStrategy): Container {
108
+ const { theme, isMulti, tabBar } = this.config;
109
+ const state = this.liveProps.state;
110
+ const container = new Container();
111
+ const border = () => new DynamicBorder((s) => theme.fg("accent", s));
107
112
 
108
- container.addChild(border());
109
- if (isMulti && tabBar) container.addChild(tabBar);
110
- container.addChild(new Spacer(1));
113
+ container.addChild(border());
114
+ if (isMulti && tabBar) container.addChild(tabBar);
115
+ container.addChild(new Spacer(1));
111
116
 
112
- for (const c of strategy.headingRows(state)) container.addChild(c);
113
- container.addChild(strategy.bodyComponent(state));
114
- container.addChild(new Spacer(1));
115
- for (const c of strategy.midRows(state)) container.addChild(c);
117
+ for (const c of strategy.headingRows(state)) container.addChild(c);
118
+ container.addChild(strategy.bodyComponent(state));
119
+ container.addChild(new Spacer(1));
120
+ for (const c of strategy.midRows(state)) container.addChild(c);
116
121
 
117
- container.addChild(border());
118
- for (const c of strategy.footerRows(state)) container.addChild(c);
122
+ container.addChild(border());
123
+ for (const c of strategy.footerRows(state)) container.addChild(c);
119
124
 
120
- // Residual spacer equalizes total height across strategies; rendered AFTER the bottom border.
121
- container.addChild(
122
- new BodyResidualSpacer(
123
- (w) => config.getBodyHeight(w) + maxFooterRowCount,
124
- (w) => strategy.bodyHeight(w, state) + strategy.footerRowCount,
125
- ),
126
- );
127
- return container;
125
+ // Residual spacer equalizes total height across strategies; rendered AFTER the bottom border.
126
+ container.addChild(
127
+ new BodyResidualSpacer(
128
+ (w) => this.config.getBodyHeight(w) + this.maxFooterRowCount,
129
+ (w) => strategy.bodyHeight(w, state) + strategy.footerRowCount,
130
+ ),
131
+ );
132
+ return container;
133
+ }
128
134
  }
@@ -1,102 +1,108 @@
1
1
  import type { InputBuffer } from "../state/input-buffer.js";
2
+ import type { BindingContext, PerTabBindingContext } from "../state/selectors/contract.js";
2
3
  import { selectActivePreviewPaneIndex } from "../state/selectors/derivations.js";
3
4
  import { selectActiveView } from "../state/selectors/focus.js";
4
- import {
5
- selectChatRowProps,
6
- selectMultiSelectProps,
7
- selectOptionListProps,
8
- selectPreviewPaneProps,
9
- selectSubmitPickerProps,
10
- selectTabBarProps,
11
- } from "../state/selectors/projections.js";
12
5
  import type { QuestionnaireState } from "../state/state.js";
13
6
  import type { QuestionData } from "../tool/types.js";
14
- import type { ChatRowView } from "./components/chat-row-view.js";
15
- import type { SubmitPicker } from "./components/submit-picker.js";
16
- import type { TabBar } from "./components/tab-bar.js";
7
+ import type { BoundGlobalBinding, BoundPerTabBinding } from "./component-binding.js";
17
8
  import type { WrappingSelectItem } from "./components/wrapping-select.js";
18
- import type { DialogProps } from "./dialog-builder.js";
19
- import type { StatefulView } from "./stateful-view.js";
20
9
  import type { TabComponents } from "./tab-components.js";
21
10
 
11
+ /** Cache-invalidation contract used by the adapter. `pi-tui` `Component` already satisfies it. */
12
+ interface Invalidatable {
13
+ invalidate(): void;
14
+ }
15
+
22
16
  export interface QuestionnairePropsAdapterConfig {
23
17
  tui: { requestRender(): void };
24
18
  questions: readonly QuestionData[];
25
19
  itemsByTab: ReadonlyArray<readonly WrappingSelectItem[]>;
26
20
  tabsByIndex: ReadonlyArray<TabComponents>;
27
- chatRow: ChatRowView;
28
- submitPicker: SubmitPicker | undefined;
29
- tabBar: TabBar | undefined;
30
- dialog: StatefulView<DialogProps>;
31
21
  inputBuffer: InputBuffer;
22
+ globalBindings: ReadonlyArray<BoundGlobalBinding>;
23
+ perTabBindings: ReadonlyArray<BoundPerTabBinding>;
24
+ /**
25
+ * Renderables not reached by the binding registries (e.g. the notes
26
+ * `Input`, which is typed into directly and has no props). Walked by
27
+ * `invalidate()` after the binding-driven components.
28
+ */
29
+ extraInvalidatables?: ReadonlyArray<Invalidatable>;
32
30
  }
33
31
 
34
32
  /**
35
- * View fan-out: drives every component setter from the canonical state via named selectors.
36
- * The `inputBuffer` cell is read per tick so `selectOptionListProps` sees the live value.
33
+ * View fan-out: drives every component setter from the canonical state via
34
+ * two binding registries. `globalBindings` covers the cross-tab components
35
+ * (chatRow, dialog, submitPicker?, tabBar?); `perTabBindings` covers the
36
+ * per-tab kinds (optionList, preview, multiSelect?). The hand-coded fan-out
37
+ * collapses to one global loop + one nested per-tab loop. The `inputBuffer`
38
+ * cell is read per tick into ctx so `selectOptionListProps` sees the live
39
+ * value.
37
40
  */
38
41
  export class QuestionnairePropsAdapter {
39
42
  private readonly tui: QuestionnairePropsAdapterConfig["tui"];
40
43
  private readonly questions: readonly QuestionData[];
41
44
  private readonly itemsByTab: ReadonlyArray<readonly WrappingSelectItem[]>;
42
45
  private readonly tabsByIndex: ReadonlyArray<TabComponents>;
43
- private readonly chatRow: ChatRowView;
44
- private readonly submitPicker: SubmitPicker | undefined;
45
- private readonly tabBar: TabBar | undefined;
46
- private readonly dialog: StatefulView<DialogProps>;
47
46
  private readonly inputBuffer: InputBuffer;
47
+ private readonly globalBindings: ReadonlyArray<BoundGlobalBinding>;
48
+ private readonly perTabBindings: ReadonlyArray<BoundPerTabBinding>;
49
+ private readonly extraInvalidatables: ReadonlyArray<Invalidatable>;
48
50
 
49
51
  constructor(config: QuestionnairePropsAdapterConfig) {
50
52
  this.tui = config.tui;
51
53
  this.questions = config.questions;
52
54
  this.itemsByTab = config.itemsByTab;
53
55
  this.tabsByIndex = config.tabsByIndex;
54
- this.chatRow = config.chatRow;
55
- this.submitPicker = config.submitPicker;
56
- this.tabBar = config.tabBar;
57
- this.dialog = config.dialog;
58
56
  this.inputBuffer = config.inputBuffer;
57
+ this.globalBindings = config.globalBindings;
58
+ this.perTabBindings = config.perTabBindings;
59
+ this.extraInvalidatables = config.extraInvalidatables ?? [];
59
60
  }
60
61
 
61
62
  apply(state: QuestionnaireState): void {
62
63
  const totalQuestions = this.questions.length;
63
64
  const activeView = selectActiveView(state, totalQuestions);
64
-
65
65
  const paneIndex = selectActivePreviewPaneIndex(state.currentTab, totalQuestions);
66
66
  const activePreviewPane = this.tabsByIndex[paneIndex]?.preview ?? this.tabsByIndex[0]!.preview;
67
67
 
68
- this.dialog.setProps({ state, activePreviewPane });
68
+ const ctx: BindingContext = {
69
+ questions: this.questions,
70
+ itemsByTab: this.itemsByTab,
71
+ totalQuestions,
72
+ activeView,
73
+ inputBuffer: this.inputBuffer.get(),
74
+ activePreviewPane,
75
+ };
76
+
77
+ for (const binding of this.globalBindings) {
78
+ binding.apply(state, ctx);
79
+ }
69
80
 
70
81
  for (let i = 0; i < this.tabsByIndex.length; i++) {
71
82
  const tab = this.tabsByIndex[i]!;
72
- const q = this.questions[i];
73
- if (i === paneIndex) {
74
- tab.optionList.setProps(
75
- selectOptionListProps(
76
- state,
77
- this.itemsByTab[i] ?? [],
78
- this.questions,
79
- activeView,
80
- this.inputBuffer.get(),
81
- ),
82
- );
83
- tab.preview.setProps(selectPreviewPaneProps(state, activeView));
84
- }
85
- if (tab.multiSelect && q) {
86
- tab.multiSelect.setProps(selectMultiSelectProps(state, q, activeView));
83
+ const tabCtx: PerTabBindingContext = { ...ctx, tab, i };
84
+ for (const binding of this.perTabBindings) {
85
+ binding.apply(state, tabCtx);
87
86
  }
88
87
  }
89
88
 
90
- this.chatRow.setProps(selectChatRowProps(state, this.itemsByTab, totalQuestions, activeView));
91
-
92
- if (this.submitPicker) {
93
- this.submitPicker.setProps(selectSubmitPickerProps(state, totalQuestions, activeView));
94
- }
89
+ this.tui.requestRender();
90
+ }
95
91
 
96
- if (this.tabBar) {
97
- this.tabBar.setProps(selectTabBarProps(state, this.questions));
92
+ /**
93
+ * Invalidates every owned renderable. Called by the session in place of
94
+ * the old `dialog.invalidate()` forwarding chain — DialogView no longer
95
+ * reaches into siblings (chatRow, tabBar, notesInput, activePreviewPane).
96
+ * Iterates the same registries used by `apply()` plus
97
+ * `extraInvalidatables` for components outside the binding system.
98
+ */
99
+ invalidate(): void {
100
+ for (const b of this.globalBindings) b.invalidate();
101
+ for (const tab of this.tabsByIndex) {
102
+ tab.optionList.invalidate();
103
+ tab.preview.invalidate();
104
+ tab.multiSelect?.invalidate();
98
105
  }
99
-
100
- this.tui.requestRender();
106
+ for (const x of this.extraInvalidatables) x.invalidate();
101
107
  }
102
108
  }
@@ -1,10 +1,18 @@
1
- import type { MultiSelectView } from "./components/multi-select-view.js";
2
- import type { OptionListView } from "./components/option-list-view.js";
3
- import type { PreviewPane } from "./components/preview/preview-pane.js";
1
+ import type { MultiSelectViewProps } from "./components/multi-select-view.js";
2
+ import type { OptionListViewProps } from "./components/option-list-view.js";
3
+ import type { PreviewPaneProps } from "./components/preview/preview-pane.js";
4
+ import type { StatefulView } from "./stateful-view.js";
4
5
 
5
- /** Per-question view components. `multiSelect` is undefined for single-select questions. */
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
14
  export interface TabComponents {
7
- optionList: OptionListView;
8
- preview: PreviewPane;
9
- multiSelect?: MultiSelectView;
15
+ optionList: StatefulView<OptionListViewProps>;
16
+ preview: StatefulView<PreviewPaneProps>;
17
+ multiSelect?: StatefulView<MultiSelectViewProps>;
10
18
  }
@@ -3,7 +3,7 @@ import { type Component, Container, type Input, Spacer, Text } from "@mariozechn
3
3
  import { formatAnswerScalar } from "../tool/format-answer.js";
4
4
  import type { QuestionData } from "../tool/types.js";
5
5
  import type { ChatRowView } from "./components/chat-row-view.js";
6
- import type { PreviewPane } from "./components/preview/preview-pane.js";
6
+ import type { PreviewPaneProps } from "./components/preview/preview-pane.js";
7
7
  import {
8
8
  type DialogState,
9
9
  HINT_PART_CANCEL,
@@ -16,6 +16,7 @@ import {
16
16
  READY_PROMPT,
17
17
  REVIEW_HEADING,
18
18
  } from "./dialog-builder.js";
19
+ import type { StatefulView } from "./stateful-view.js";
19
20
  import type { TabComponents } from "./tab-components.js";
20
21
 
21
22
  /**
@@ -46,7 +47,7 @@ export interface TabContentStrategy {
46
47
  export interface QuestionTabStrategyConfig {
47
48
  theme: Theme;
48
49
  questions: readonly QuestionData[];
49
- getPreviewPane: () => PreviewPane;
50
+ getPreviewPane: () => StatefulView<PreviewPaneProps>;
50
51
  tabsByIndex: ReadonlyArray<TabComponents>;
51
52
  notesInput: Input;
52
53
  chatRow: ChatRowView;