@juicesharp/rpiv-ask-user-question 1.8.2 → 1.9.0

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.8.2",
3
+ "version": "1.9.0",
4
4
  "description": "Pi extension. A structured questionnaire the model can put to you when it would otherwise guess, with typed options instead of free-form replies.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -47,7 +47,6 @@
47
47
  "tool/response-envelope.ts",
48
48
  "tool/types.ts",
49
49
  "tool/validate-questionnaire.ts",
50
- "view/body-residual-spacer.ts",
51
50
  "view/component-binding.ts",
52
51
  "view/components/chat-row-view.ts",
53
52
  "view/components/multi-select-view.ts",
@@ -83,6 +82,6 @@
83
82
  }
84
83
  },
85
84
  "dependencies": {
86
- "@juicesharp/rpiv-config": "^1.8.2"
85
+ "@juicesharp/rpiv-config": "^1.9.0"
87
86
  }
88
87
  }
@@ -36,7 +36,7 @@ import {
36
36
  import type { QuestionnaireState } from "./state.js";
37
37
 
38
38
  export interface QuestionnaireBuildConfig {
39
- tui: { terminal: { columns: number }; requestRender(): void };
39
+ tui: { terminal: { columns: number; rows: number }; requestRender(): void };
40
40
  theme: Theme;
41
41
  questions: readonly QuestionData[];
42
42
  itemsByTab: ReadonlyArray<readonly WrappingSelectItem[]>;
@@ -106,6 +106,7 @@ class QuestionnaireBuilder {
106
106
  private readonly notesInput = new Input();
107
107
  private readonly inlineInput = new Input();
108
108
  private readonly getTerminalWidth = () => this.tui.terminal.columns;
109
+ private readonly getTerminalRows = () => this.tui.terminal.rows;
109
110
 
110
111
  constructor(config: QuestionnaireBuildConfig) {
111
112
  this.tui = config.tui;
@@ -242,6 +243,7 @@ class QuestionnaireBuilder {
242
243
  submitPicker,
243
244
  getBodyHeight: heights.global,
244
245
  getCurrentBodyHeight: heights.current,
246
+ getTerminalRows: this.getTerminalRows,
245
247
  },
246
248
  { state: this.initialState, activePreviewPane: this.pickInitialActivePreview(tabs) },
247
249
  );
@@ -15,7 +15,7 @@ import { type ApplyContext, type Effect, reduce } from "./state-reducer.js";
15
15
  const CURSOR_END = "\x05";
16
16
 
17
17
  export interface QuestionnaireSessionConfig {
18
- tui: { terminal: { columns: number }; requestRender(): void };
18
+ tui: { terminal: { columns: number; rows: number }; requestRender(): void };
19
19
  theme: Theme;
20
20
  params: QuestionParams;
21
21
  itemsByTab: WrappingSelectItem[][];
@@ -84,6 +84,30 @@ export class MultiSelectView implements StatefulView<MultiSelectViewProps> {
84
84
  return lines;
85
85
  }
86
86
 
87
+ /**
88
+ * Returns the [startRow, endRow) range of the active (focused) row within
89
+ * `render(width)`. Labels are always 1 row (truncated); descriptions wrap.
90
+ */
91
+ focusedItemRowRange(width: number): [number, number] {
92
+ const prefixWidth = this.prefixVisibleWidth();
93
+ const contentWidth = Math.max(1, width - prefixWidth);
94
+ let row = 0;
95
+ for (let i = 0; i < this.question.options.length; i++) {
96
+ const opt = this.question.options[i];
97
+ const r = this.props.rows[i];
98
+ if (!opt || !r) continue;
99
+ const itemHeight = 1 + (opt.description ? wrapTextWithAnsi(opt.description, contentWidth).length : 0);
100
+ if (r.active) {
101
+ return [row, row + itemHeight];
102
+ }
103
+ row += itemHeight;
104
+ }
105
+ if (this.props.nextActive) {
106
+ return [row, row + 1];
107
+ }
108
+ return [0, 0];
109
+ }
110
+
87
111
  naturalHeight(width: number): number {
88
112
  const contentWidth = Math.max(1, width - this.prefixVisibleWidth());
89
113
  let total = 0;
@@ -62,4 +62,8 @@ export class OptionListView implements StatefulView<OptionListViewProps> {
62
62
  render(width: number): string[] {
63
63
  return this.select.render(width);
64
64
  }
65
+
66
+ focusedItemRowRange(width: number): [number, number] {
67
+ return this.select.focusedItemRowRange(width);
68
+ }
65
69
  }
@@ -133,6 +133,16 @@ export class PreviewPane implements StatefulView<PreviewPaneProps>, Component {
133
133
  ];
134
134
  }
135
135
 
136
+ focusedItemRowRange(width: number): [number, number] {
137
+ if (this.question.multiSelect === true) return this.optionListView.focusedItemRowRange(width);
138
+ if (!this.previewBlock.hasAnyPreview()) return this.optionListView.focusedItemRowRange(width);
139
+ const mode = decideLayout(this.getTerminalWidth(), width);
140
+ if (mode === "stacked") return this.optionListView.focusedItemRowRange(width);
141
+ const adaptiveLeft = this.getAdaptiveLeft(width);
142
+ const { leftWidth } = columnWidths(width, adaptiveLeft);
143
+ return this.optionListView.focusedItemRowRange(leftWidth);
144
+ }
145
+
136
146
  naturalHeight(width: number): number {
137
147
  if (this.question.multiSelect === true) return this.optionListView.render(width).length;
138
148
  if (!this.previewBlock.hasAnyPreview()) return this.optionListView.render(width).length;
@@ -150,6 +150,44 @@ export class WrappingSelect implements Component {
150
150
  return lines;
151
151
  }
152
152
 
153
+ /**
154
+ * Returns the [startRow, endRow) range of the focused (selected) item within
155
+ * the output of `render(width)`. Computed by iterating the visible window and
156
+ * summing per-item row counts — O(maxVisible) per call.
157
+ */
158
+ focusedItemRowRange(width: number): [number, number] {
159
+ if (this.items.length === 0) return [0, 0];
160
+ const { startIndex, endIndex } = this.computeVisibleWindow();
161
+ const numberWidth = String(Math.max(1, this.totalItemsForNumbering)).length;
162
+ let row = 0;
163
+ for (let i = startIndex; i < endIndex; i++) {
164
+ const item = this.items[i];
165
+ if (!item) continue;
166
+ const isActive = i === this.selectedIndex && this.focused;
167
+ const itemRowCount = this.computeItemRowCount(item, i, isActive, width, numberWidth);
168
+ if (i === this.selectedIndex) {
169
+ return [row, row + itemRowCount];
170
+ }
171
+ row += itemRowCount;
172
+ }
173
+ return [0, 1];
174
+ }
175
+
176
+ /**
177
+ * Per-item row count. Delegates to `renderItem().length` so `renderItem` remains
178
+ * the single source of truth for per-item row math — eliminates the prior shadow-copy
179
+ * that risked silent miscounts when new `kind` values branch in `renderItem` but not here.
180
+ */
181
+ private computeItemRowCount(
182
+ item: WrappingSelectItem,
183
+ index: number,
184
+ isActive: boolean,
185
+ width: number,
186
+ numberWidth: number,
187
+ ): number {
188
+ return this.renderItem(item, index, isActive, width, numberWidth).length;
189
+ }
190
+
153
191
  private computeVisibleWindow(): { startIndex: number; endIndex: number } {
154
192
  const half = Math.floor(this.maxVisible / 2);
155
193
  const startIndex = Math.max(0, Math.min(this.selectedIndex - half, this.items.length - this.maxVisible));
@@ -2,7 +2,6 @@ import { DynamicBorder, type Theme } from "@earendil-works/pi-coding-agent";
2
2
  import { type Component, Container, type Input, Spacer } from "@earendil-works/pi-tui";
3
3
  import type { QuestionnaireState } from "../state/state.js";
4
4
  import type { QuestionData } from "../tool/types.js";
5
- import { BodyResidualSpacer } from "./body-residual-spacer.js";
6
5
  import type { ChatRowView } from "./components/chat-row-view.js";
7
6
  import type { PreviewPaneProps } from "./components/preview/preview-pane.js";
8
7
  import type { TabBar } from "./components/tab-bar.js";
@@ -24,6 +23,10 @@ export const REVIEW_HEADING = "Review your answers";
24
23
  export const READY_PROMPT = "Ready to submit your answers?";
25
24
  export const INCOMPLETE_WARNING_PREFIX = "⚠ Answer remaining questions before submitting:";
26
25
 
26
+ const OVERFLOW_UP = "↑";
27
+ const OVERFLOW_DOWN = "↓";
28
+ const OVERFLOW_BOTH = "↕";
29
+
27
30
  export type DialogState = QuestionnaireState;
28
31
 
29
32
  /** Per-tick projection of dialog state. Written by the adapter; read by the strategy thunk. */
@@ -47,6 +50,8 @@ export interface DialogConfig {
47
50
  getBodyHeight: (width: number) => number;
48
51
  /** Body height of the CURRENTLY active tab/option. The chrome subtracts this from `getBodyHeight` to absorb the residual OUTSIDE the bordered region. */
49
52
  getCurrentBodyHeight: (width: number) => number;
53
+ /** Terminal height getter. Mirrors `getTerminalWidth` — reads `tui.terminal.rows` at render time. */
54
+ getTerminalRows: () => number;
50
55
  }
51
56
 
52
57
  /**
@@ -99,12 +104,89 @@ export class DialogView implements StatefulView<DialogProps> {
99
104
  invalidate(): void {}
100
105
 
101
106
  render(width: number): string[] {
102
- const onSubmit = this.config.isMulti && this.liveProps.state.currentTab === this.config.questions.length;
107
+ const state = this.liveProps.state;
108
+ const onSubmit = this.config.isMulti && state.currentTab === this.config.questions.length;
103
109
  const strategy = onSubmit && this.submitStrategy ? this.submitStrategy : this.questionStrategy;
104
- return this.buildContainerFromStrategy(strategy).render(width);
110
+
111
+ // Cache heading rows (avoid double construction in render and container build).
112
+ const headingRowCache = strategy.headingRows(state);
113
+ const headingCount = headingRowCache.length;
114
+
115
+ // Build container WITHOUT residual spacer — spacer handled below based on overflow.
116
+ const natural = this.buildContainerFromStrategy(strategy, headingRowCache).render(width);
117
+
118
+ // Fixed region sizes (deterministic from structure).
119
+ // TabBar.render() returns [tabLine, ""] — always 2 rows.
120
+ const topFixed = 1 + (this.config.isMulti && this.config.tabBar ? 2 : 0) + 1;
121
+ const bottomFixed = 1 + strategy.footerRowCount;
122
+ const middleRows = natural.length - topFixed - bottomFixed;
123
+
124
+ // Residual spacer: equalizes total height across tabs (only needed when no overflow).
125
+ const spacerRows = Math.max(
126
+ 0,
127
+ this.config.getBodyHeight(width) +
128
+ this.maxFooterRowCount -
129
+ strategy.bodyHeight(width, state) -
130
+ strategy.footerRowCount,
131
+ );
132
+
133
+ const termRows = this.config.getTerminalRows();
134
+
135
+ if (natural.length + spacerRows <= termRows) {
136
+ // No overflow — add residual spacer rows after footer.
137
+ return spacerRows > 0 ? [...natural, ...Array<string>(spacerRows).fill("")] : natural;
138
+ }
139
+
140
+ // OVERFLOW — apply 3-region partition with scroll-to-focus.
141
+ const availableMiddle = Math.max(0, termRows - topFixed - bottomFixed);
142
+ if (availableMiddle === 0) {
143
+ // Terminal too small for any middle content — show just chrome.
144
+ const chromeOnly = [...natural.slice(0, topFixed), ...natural.slice(natural.length - bottomFixed)];
145
+ return chromeOnly.length > termRows ? chromeOnly.slice(0, termRows) : chromeOnly;
146
+ }
147
+
148
+ const bodyRange = strategy.focusedItemRowRange(width, state);
149
+
150
+ // Compute scroll window centered on the focused option.
151
+ let scrollStart: number;
152
+ if (bodyRange) {
153
+ const focusedRowInMiddle = headingCount + bodyRange[0];
154
+ const focusedHeight = bodyRange[1] - bodyRange[0];
155
+ // Center the focused item vertically in the available middle space.
156
+ const idealStart = focusedRowInMiddle - Math.floor(Math.max(0, availableMiddle - focusedHeight) / 2);
157
+ scrollStart = Math.max(0, Math.min(idealStart, middleRows - availableMiddle));
158
+ } else {
159
+ // No interactive focus (submit tab) — top-anchor the middle.
160
+ scrollStart = 0;
161
+ }
162
+
163
+ const scrollableMiddle = natural.slice(topFixed + scrollStart, topFixed + scrollStart + availableMiddle);
164
+
165
+ const hasUp = scrollStart > 0;
166
+ const hasDown = scrollStart + availableMiddle < middleRows;
167
+ if (hasUp && hasDown && scrollableMiddle.length === 1) {
168
+ // Single-row middle: combined ↕ avoids the prior collision where ↓ overwrote ↑.
169
+ scrollableMiddle[0] = this.config.theme.fg("dim", OVERFLOW_BOTH);
170
+ } else {
171
+ if (hasUp && scrollableMiddle.length > 0) {
172
+ scrollableMiddle[0] = this.config.theme.fg("dim", OVERFLOW_UP);
173
+ }
174
+ if (hasDown && scrollableMiddle.length > 0) {
175
+ scrollableMiddle[scrollableMiddle.length - 1] = this.config.theme.fg("dim", OVERFLOW_DOWN);
176
+ }
177
+ }
178
+
179
+ const result = [
180
+ ...natural.slice(0, topFixed),
181
+ ...scrollableMiddle,
182
+ ...natural.slice(natural.length - bottomFixed),
183
+ ];
184
+ // Safety: never exceed terminal rows (covers the availableMiddle === 0 case
185
+ // where topFixed + bottomFixed > termRows).
186
+ return result.length > termRows ? result.slice(0, termRows) : result;
105
187
  }
106
188
 
107
- private buildContainerFromStrategy(strategy: TabContentStrategy): Container {
189
+ private buildContainerFromStrategy(strategy: TabContentStrategy, headingRowCache: Component[]): Container {
108
190
  const { theme, isMulti, tabBar } = this.config;
109
191
  const state = this.liveProps.state;
110
192
  const container = new Container();
@@ -114,7 +196,7 @@ export class DialogView implements StatefulView<DialogProps> {
114
196
  if (isMulti && tabBar) container.addChild(tabBar);
115
197
  container.addChild(new Spacer(1));
116
198
 
117
- for (const c of strategy.headingRows(state)) container.addChild(c);
199
+ for (const c of headingRowCache) container.addChild(c);
118
200
  container.addChild(strategy.bodyComponent(state));
119
201
  container.addChild(new Spacer(1));
120
202
  for (const c of strategy.midRows(state)) container.addChild(c);
@@ -122,13 +204,7 @@ export class DialogView implements StatefulView<DialogProps> {
122
204
  container.addChild(border());
123
205
  for (const c of strategy.footerRows(state)) container.addChild(c);
124
206
 
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
- );
207
+ // BodyResidualSpacer moved out of Container — handled in render().
132
208
  return container;
133
209
  }
134
210
  }
@@ -1,4 +1,4 @@
1
- import type { MultiSelectViewProps } from "./components/multi-select-view.js";
1
+ import type { MultiSelectView } from "./components/multi-select-view.js";
2
2
  import type { OptionListViewProps } from "./components/option-list-view.js";
3
3
  import type { PreviewPane } from "./components/preview/preview-pane.js";
4
4
  import type { StatefulView } from "./stateful-view.js";
@@ -11,6 +11,6 @@ export interface TabBodyHeights {
11
11
  export interface TabComponents {
12
12
  optionList: StatefulView<OptionListViewProps>;
13
13
  preview: PreviewPane;
14
- multiSelect?: StatefulView<MultiSelectViewProps>;
14
+ multiSelect?: MultiSelectView;
15
15
  bodyHeights: (width: number) => TabBodyHeights;
16
16
  }
@@ -4,7 +4,7 @@ import { t } from "../state/i18n-bridge.js";
4
4
  import { formatAnswerScalar } from "../tool/format-answer.js";
5
5
  import type { QuestionData } from "../tool/types.js";
6
6
  import type { ChatRowView } from "./components/chat-row-view.js";
7
- import type { PreviewPaneProps } from "./components/preview/preview-pane.js";
7
+ import type { PreviewPane, PreviewPaneProps } from "./components/preview/preview-pane.js";
8
8
  import {
9
9
  type DialogState,
10
10
  HINT_PART_CANCEL,
@@ -45,6 +45,9 @@ export interface TabContentStrategy {
45
45
 
46
46
  /** Footer rows below the bottom border. Rendered row count MUST equal `footerRowCount`. */
47
47
  footerRows(state: DialogState): Component[];
48
+
49
+ /** Row range of the focused item within the body's rendered output, or undefined if no interactive focus. */
50
+ focusedItemRowRange(width: number, state: DialogState): [number, number] | undefined;
48
51
  }
49
52
 
50
53
  export interface QuestionTabStrategyConfig {
@@ -108,6 +111,13 @@ export class QuestionTabStrategy implements TabContentStrategy {
108
111
  new Text(this.config.theme.fg("dim", buildHintText(question, this.config.isMulti, state)), 1, 0),
109
112
  ];
110
113
  }
114
+
115
+ focusedItemRowRange(width: number, state: DialogState): [number, number] | undefined {
116
+ const question = this.config.questions[state.currentTab];
117
+ const mso = this.config.tabsByIndex[state.currentTab]?.multiSelect;
118
+ if (question?.multiSelect === true && mso) return mso.focusedItemRowRange(width);
119
+ return (this.config.getPreviewPane() as unknown as PreviewPane).focusedItemRowRange(width);
120
+ }
111
121
  }
112
122
 
113
123
  export interface SubmitTabStrategyConfig {
@@ -181,6 +191,10 @@ export class SubmitTabStrategy implements TabContentStrategy {
181
191
  }
182
192
  return out;
183
193
  }
194
+
195
+ focusedItemRowRange(_width: number, _state: DialogState): [number, number] | undefined {
196
+ return undefined;
197
+ }
184
198
  }
185
199
 
186
200
  /**
@@ -1,25 +0,0 @@
1
- import type { Component } from "@earendil-works/pi-tui";
2
-
3
- /**
4
- * Emits `max(0, getMax(width) - getCurrent(width))` empty rows. Used in
5
- * `dialog-builder.ts` to absorb the dialog-height residual OUTSIDE the bordered
6
- * body region: the body renders at its natural height (no internal `""`
7
- * padding), and this spacer makes up the difference between the global max
8
- * across tabs and the current tab's body height so the overall dialog footprint
9
- * stays constant on tab switches.
10
- */
11
- export class BodyResidualSpacer implements Component {
12
- constructor(
13
- private readonly getMax: (width: number) => number,
14
- private readonly getCurrent: (width: number) => number,
15
- ) {}
16
-
17
- handleInput(_data: string): void {}
18
-
19
- invalidate(): void {}
20
-
21
- render(width: number): string[] {
22
- const diff = Math.max(0, this.getMax(width) - this.getCurrent(width));
23
- return Array<string>(diff).fill("");
24
- }
25
- }