@juicesharp/rpiv-ask-user-question 1.8.3 → 1.9.1

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/README.md CHANGED
@@ -23,6 +23,7 @@ Let the model ask you structured clarifying questions instead of guessing. `rpiv
23
23
  - **Multi-select questions** - checkboxes with `Space` to toggle, Enter-as-toggle on rows, a `Next` sentinel to advance, and toggles persisted across tab switches.
24
24
  - **Submit tab** - review every answer before submitting; warns about unanswered questions and offers a Submit picker.
25
25
  - **Chat row on every tab** - redirect the conversation without leaving the dialog.
26
+ - **Terminal-row-aware overflow scroll** - when the dialog is taller than the terminal, the body scrolls between a sticky heading and sticky hints/border; overflow indicators (↑ / ↓ / ↕) show what's clipped.
26
27
  - **"Other" free-text fallback** - type a custom answer when no option fits.
27
28
  - **Localized UI** - sentinel rows, hints, submit/cancel labels, review pane, and notes affordance display in the user's chosen language via `@juicesharp/rpiv-i18n`. Ships Deutsch / English / Español / Français / Português (PT) / Português (BR) / Русский / Українська; switch with `/languages` or `pi --locale <code>`. LLM-facing copy (tool description, schemas, errors) stays English by design.
28
29
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-ask-user-question",
3
- "version": "1.8.3",
3
+ "version": "1.9.1",
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.3"
85
+ "@juicesharp/rpiv-config": "^1.9.1"
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[][];
@@ -11,6 +11,7 @@ export interface BindingContext {
11
11
  readonly totalQuestions: number;
12
12
  readonly activeView: ActiveView;
13
13
  readonly inputBuffer: string;
14
+ readonly inputCursorOffset: number | undefined;
14
15
  readonly activePreviewPane: StatefulView<PreviewPaneProps>;
15
16
  }
16
17
 
@@ -34,6 +34,7 @@ export const selectOptionListProps: PerTabSelector<OptionListViewProps> = (state
34
34
  selectedIndex: state.optionIndex,
35
35
  focused,
36
36
  inputBuffer: ctx.inputBuffer,
37
+ inputCursorOffset: ctx.inputCursorOffset,
37
38
  ...(confirmed ? { confirmed } : {}),
38
39
  };
39
40
  };
@@ -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;
@@ -23,6 +23,7 @@ export interface OptionListViewProps {
23
23
  selectedIndex: number;
24
24
  focused: boolean;
25
25
  inputBuffer: string;
26
+ inputCursorOffset?: number;
26
27
  /** Optional previously-confirmed indicator. Omit when no marker should be drawn. */
27
28
  confirmed?: { index: number; labelOverride?: string };
28
29
  }
@@ -51,6 +52,7 @@ export class OptionListView implements StatefulView<OptionListViewProps> {
51
52
  this.select.setFocused(props.focused);
52
53
  this.select.setConfirmedIndex(props.confirmed?.index, props.confirmed?.labelOverride);
53
54
  this.select.setInputBuffer(props.inputBuffer);
55
+ this.select.setInputCursorOffset(props.inputCursorOffset);
54
56
  }
55
57
 
56
58
  handleInput(_data: string): void {}
@@ -62,4 +64,8 @@ export class OptionListView implements StatefulView<OptionListViewProps> {
62
64
  render(width: number): string[] {
63
65
  return this.select.render(width);
64
66
  }
67
+
68
+ focusedItemRowRange(width: number): [number, number] {
69
+ return this.select.focusedItemRowRange(width);
70
+ }
65
71
  }
@@ -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;
@@ -1,5 +1,11 @@
1
1
  import type { Component } from "@earendil-works/pi-tui";
2
- import { visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
2
+ import { CURSOR_MARKER, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
3
+
4
+ // Grapheme-aware extraction at the cursor: pi-tui's Input advances `cursor` by
5
+ // grapheme-cluster code-unit length, so the cursor can land between code units of
6
+ // one cluster (emoji, ZWJ, combining marks). Single-code-unit slicing would split
7
+ // the cluster across the SGR 7/27 boundary.
8
+ const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
3
9
 
4
10
  /**
5
11
  * Row-intent discriminated union. `kind` is the single discriminator —
@@ -47,7 +53,6 @@ export class WrappingSelect implements Component {
47
53
  private static readonly ACTIVE_POINTER = "❯ ";
48
54
  private static readonly INACTIVE_POINTER = " ";
49
55
  private static readonly NUMBER_SEPARATOR = ". ";
50
- private static readonly INPUT_CURSOR = "▌";
51
56
  private static readonly CONFIRMED_MARK = " ✔";
52
57
  private static readonly MIN_CONTENT_WIDTH = 1;
53
58
 
@@ -60,6 +65,7 @@ export class WrappingSelect implements Component {
60
65
  private selectedIndex = 0;
61
66
  private focused = true;
62
67
  private inputBuffer = "";
68
+ private inputCursorOffset: number | undefined = undefined;
63
69
  /**
64
70
  * Index of the row that was previously confirmed for this list (e.g. the user's prior
65
71
  * answer when re-entering a multi-question tab). Renders `<label> ✔` in the active-row
@@ -125,6 +131,11 @@ export class WrappingSelect implements Component {
125
131
  this.inputBuffer = text;
126
132
  }
127
133
 
134
+ /** Set the cursor offset for the inline input row. `undefined` → end-of-buffer fallback. */
135
+ setInputCursorOffset(offset: number | undefined): void {
136
+ this.inputCursorOffset = offset;
137
+ }
138
+
128
139
  /** Intentionally empty — input is routed at the container level. */
129
140
  handleInput(_data: string): void {}
130
141
 
@@ -150,6 +161,44 @@ export class WrappingSelect implements Component {
150
161
  return lines;
151
162
  }
152
163
 
164
+ /**
165
+ * Returns the [startRow, endRow) range of the focused (selected) item within
166
+ * the output of `render(width)`. Computed by iterating the visible window and
167
+ * summing per-item row counts — O(maxVisible) per call.
168
+ */
169
+ focusedItemRowRange(width: number): [number, number] {
170
+ if (this.items.length === 0) return [0, 0];
171
+ const { startIndex, endIndex } = this.computeVisibleWindow();
172
+ const numberWidth = String(Math.max(1, this.totalItemsForNumbering)).length;
173
+ let row = 0;
174
+ for (let i = startIndex; i < endIndex; i++) {
175
+ const item = this.items[i];
176
+ if (!item) continue;
177
+ const isActive = i === this.selectedIndex && this.focused;
178
+ const itemRowCount = this.computeItemRowCount(item, i, isActive, width, numberWidth);
179
+ if (i === this.selectedIndex) {
180
+ return [row, row + itemRowCount];
181
+ }
182
+ row += itemRowCount;
183
+ }
184
+ return [0, 1];
185
+ }
186
+
187
+ /**
188
+ * Per-item row count. Delegates to `renderItem().length` so `renderItem` remains
189
+ * the single source of truth for per-item row math — eliminates the prior shadow-copy
190
+ * that risked silent miscounts when new `kind` values branch in `renderItem` but not here.
191
+ */
192
+ private computeItemRowCount(
193
+ item: WrappingSelectItem,
194
+ index: number,
195
+ isActive: boolean,
196
+ width: number,
197
+ numberWidth: number,
198
+ ): number {
199
+ return this.renderItem(item, index, isActive, width, numberWidth).length;
200
+ }
201
+
153
202
  private computeVisibleWindow(): { startIndex: number; endIndex: number } {
154
203
  const half = Math.floor(this.maxVisible / 2);
155
204
  const startIndex = Math.max(0, Math.min(this.selectedIndex - half, this.items.length - this.maxVisible));
@@ -210,14 +259,43 @@ export class WrappingSelect implements Component {
210
259
  * so long input doesn't run off the right edge or trip the parent renderer's
211
260
  * width invariant. Mirrors `renderLabelBlock`'s contract: first line carries
212
261
  * `rowPrefix`, continuation lines carry `continuationPrefix` (spaces), and every
213
- * emitted line passes through `theme.selectedText`. The trailing cursor glyph
214
- * `▌` is appended to the buffer pre-wrap so it lands at the visual end of the
215
- * input — `Input` only exposes `getValue()` (cursor offset is private), so
216
- * cursor-mid-string is intentionally not rendered here; that would require
217
- * either an `Input.getCursorOffset()` API or delegating to `Input.render`.
262
+ * emitted line passes through `theme.selectedText`.
263
+ *
264
+ * Cursor visualization follows the standard TUI input-widget pattern (ECMA-48
265
+ * SGR 7 reverse-video on the cell *at* the cursor, not an inserted glyph) —
266
+ * same approach used by pi-tui Input.render (input.js:411-418), ink-text-input,
267
+ * terkelg/prompts, ratatui's user-input example, etc. Split: `before | at | after`
268
+ * where `at` is the single character under the cursor (or U+00A0 NBSP at end-of-
269
+ * buffer) wrapped in `\x1b[7m…\x1b[27m`. No characters shift; the column under
270
+ * the cursor inverts.
271
+ *
272
+ * pi-tui's zero-width `CURSOR_MARKER` (APC sentinel) is emitted immediately
273
+ * before the `at` cell so the TUI framebuffer can position the hardware
274
+ * terminal cursor at that column (visible iff pi's `showHardwareCursor`
275
+ * setting is on — `pi-coding-agent/main.js:303`). `visibleWidth` strips the
276
+ * marker as zero-width (utils.js:187-203), so wrap math is preserved.
277
+ *
278
+ * NBSP at end-of-buffer (rather than literal space): `wrapTextWithAnsi`
279
+ * tokenizes on whitespace, so a literal space inside the reverse-video escape
280
+ * pair would cause `wrapTextWithAnsi` to break the line at the cursor. NBSP
281
+ * preserves the visible width-1 contribution without registering as a wrap
282
+ * break — the conventional workaround documented across ANSI-aware string
283
+ * wrappers.
218
284
  */
219
285
  private renderInlineInputRow(rowPrefix: string, continuationPrefix: string, contentWidth: number): string[] {
220
- const raw = `${this.inputBuffer}${WrappingSelect.INPUT_CURSOR}`;
286
+ const buffer = this.inputBuffer;
287
+ const requested = this.inputCursorOffset;
288
+ const offset =
289
+ requested !== undefined && requested >= 0 && requested <= buffer.length ? requested : buffer.length;
290
+ const before = buffer.slice(0, offset);
291
+ const [firstGrapheme] = graphemeSegmenter.segment(buffer.slice(offset));
292
+ const rawAt = firstGrapheme ? firstGrapheme.segment : "";
293
+ // Whitespace at cursor (including end-of-buffer fallback) tokenizes as a wrap
294
+ // break inside `wrapTextWithAnsi`, splitting the line at the cursor. Substitute
295
+ // U+00A0 (NBSP): visually identical to a space, wrap-safe.
296
+ const atCursor = rawAt === "" || rawAt === " " ? " " : rawAt;
297
+ const after = buffer.slice(offset + rawAt.length);
298
+ const raw = `${before}${CURSOR_MARKER}\x1b[7m${atCursor}\x1b[27m${after}`;
221
299
  const wrapped = wrapTextWithAnsi(raw, contentWidth);
222
300
  return wrapped.map((segment, index) => {
223
301
  const prefix = index === 0 ? rowPrefix : continuationPrefix;
@@ -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
  }
@@ -13,6 +13,20 @@ interface Invalidatable {
13
13
  invalidate(): void;
14
14
  }
15
15
 
16
+ /**
17
+ * Reads pi-tui Input's private `cursor` field via type escape with full runtime validation.
18
+ * Returns `undefined` on any failure → graceful degradation to end-of-buffer cursor.
19
+ * Follow-up: replace with Input.getCursorOffset() when pi-tui exposes a public API.
20
+ */
21
+ function getInputCursorOffset(input: Input): number | undefined {
22
+ const raw = (input as unknown as { cursor?: unknown }).cursor;
23
+ if (typeof raw !== "number") return undefined;
24
+ if (!Number.isSafeInteger(raw)) return undefined;
25
+ const value = input.getValue();
26
+ if (raw < 0 || raw > value.length) return undefined;
27
+ return raw;
28
+ }
29
+
16
30
  export interface QuestionnairePropsAdapterConfig {
17
31
  tui: { requestRender(): void };
18
32
  questions: readonly QuestionData[];
@@ -71,6 +85,7 @@ export class QuestionnairePropsAdapter {
71
85
  totalQuestions,
72
86
  activeView,
73
87
  inputBuffer: this.inlineInput.getValue(),
88
+ inputCursorOffset: getInputCursorOffset(this.inlineInput),
74
89
  activePreviewPane,
75
90
  };
76
91
 
@@ -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
- }