@juicesharp/rpiv-ask-user-question 2.1.0 → 2.2.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.
@@ -1,5 +1,5 @@
1
1
  import type { Theme } from "@earendil-works/pi-coding-agent";
2
- import { getKeybindings, type Input, type OverlayHandle } from "@earendil-works/pi-tui";
2
+ import type { Editor, OverlayHandle, TUI } from "@earendil-works/pi-tui";
3
3
  import type { QuestionData, QuestionnaireResult, QuestionParams } from "../tool/types.js";
4
4
  import type { WrappingSelectItem } from "../view/components/wrapping-select.js";
5
5
  import { COLLAPSED_HINT } from "../view/dialog-builder.js";
@@ -10,16 +10,15 @@ import { type QuestionnaireAction, routeKey } from "./key-router.js";
10
10
  import type { QuestionnaireRuntime, QuestionnaireState } from "./state.js";
11
11
  import { type ApplyContext, type Effect, reduce } from "./state-reducer.js";
12
12
 
13
- // Module-level constant; reused for cursor-end mutations after setValue rehydration.
14
- // Ctrl-E → tui.editor.cursorLineEnd (public path; pi-tui keybindings.js:25-28).
15
- const CURSOR_END = "\x05";
16
-
17
13
  export interface QuestionnaireSessionConfig {
18
- tui: { terminal: { columns: number; rows: number }; requestRender(): void };
14
+ tui: TUI;
19
15
  theme: Theme;
20
16
  params: QuestionParams;
21
17
  itemsByTab: WrappingSelectItem[][];
22
18
  done: (result: QuestionnaireResult) => void;
19
+ keybindings: QuestionnaireRuntime["keybindings"];
20
+ /** Opens Pi's configured external editor. Resolve `undefined` on a reported launch failure. */
21
+ editInput: (value: string) => Promise<string | undefined>;
23
22
  /** Key spec for the collapse/expand shortcut, e.g. `"ctrl+]"` or `"alt+o"`. */
24
23
  collapseKey: string;
25
24
  }
@@ -38,6 +37,7 @@ function initialState(): QuestionnaireState {
38
37
  notesVisible: false,
39
38
  answers: new Map(),
40
39
  multiSelectChecked: new Set(),
40
+ customDraftsByTab: new Map(),
41
41
  notesByTab: new Map(),
42
42
  submitChoiceIndex: 0,
43
43
  notesDraft: "",
@@ -46,8 +46,8 @@ function initialState(): QuestionnaireState {
46
46
  }
47
47
 
48
48
  /**
49
- * Slim runtime: owns the canonical state cell, the input-buffer cell, the
50
- * two-pass `notesVisible` dispatch loop, and the effect runner. State
49
+ * Slim runtime: owns the canonical state cell, the headless editor cells, the
50
+ * notes-draft mirror, and the effect runner. State
51
51
  * transitions go through the pure `reduce` reducer; UI fan-out goes through
52
52
  * the `QuestionnairePropsAdapter` produced by `buildQuestionnaire`.
53
53
  */
@@ -58,10 +58,13 @@ export class QuestionnaireSession {
58
58
  private readonly isMulti: boolean;
59
59
  private readonly itemsByTab: WrappingSelectItem[][];
60
60
 
61
- private readonly notesInput: Input;
62
- private readonly inlineInput: Input;
61
+ private readonly notesInput: Editor;
62
+ private readonly inlineInput: Editor;
63
63
  private readonly viewAdapter: QuestionnairePropsAdapter;
64
+ private readonly keybindings: QuestionnaireRuntime["keybindings"];
65
+ private readonly editInput: QuestionnaireSessionConfig["editInput"];
64
66
  private readonly collapseKey: string;
67
+ private inputEditorOpen = false;
65
68
 
66
69
  /**
67
70
  * Overlay handle captured by `ctx.ui.custom`'s `onHandle` callback. Lets the session
@@ -80,6 +83,8 @@ export class QuestionnaireSession {
80
83
  this.questions = config.params.questions;
81
84
  this.isMulti = this.questions.length > 1;
82
85
  this.itemsByTab = config.itemsByTab;
86
+ this.keybindings = config.keybindings;
87
+ this.editInput = config.editInput;
83
88
  this.collapseKey = config.collapseKey;
84
89
 
85
90
  const built = buildQuestionnaire({
@@ -116,6 +121,7 @@ export class QuestionnaireSession {
116
121
  }
117
122
 
118
123
  dispatch(data: string): void {
124
+ if (this.inputEditorOpen) return;
119
125
  const action = routeKey(data, this.state, this.runtime());
120
126
  if (action.kind === "ignore") {
121
127
  this.handleIgnoreInline(data);
@@ -133,21 +139,34 @@ export class QuestionnaireSession {
133
139
  }
134
140
 
135
141
  private mirrorNotesDraft(s: QuestionnaireState): QuestionnaireState {
136
- const draft = this.notesInput.getValue();
142
+ const draft = this.notesInput.getText();
137
143
  return s.notesDraft === draft ? s : { ...s, notesDraft: draft };
138
144
  }
139
145
 
140
146
  private runEffect(effect: Effect): void {
141
147
  switch (effect.kind) {
142
148
  case "set_input_buffer":
143
- this.inlineInput.setValue(effect.value);
144
- this.inlineInput.handleInput(CURSOR_END);
149
+ this.inlineInput.setText(effect.value);
145
150
  return;
146
151
  case "clear_input_buffer":
147
- this.inlineInput.setValue("");
152
+ this.inlineInput.setText("");
153
+ return;
154
+ case "open_input_editor":
155
+ if (this.inputEditorOpen) return;
156
+ this.inputEditorOpen = true;
157
+ void this.editInput(effect.value).then(
158
+ (value) => {
159
+ this.inputEditorOpen = false;
160
+ if (value !== undefined) this.commit({ kind: "input_replace", value });
161
+ },
162
+ () => {
163
+ // The host callback reports launch errors; retain the draft and restore input handling.
164
+ this.inputEditorOpen = false;
165
+ },
166
+ );
148
167
  return;
149
168
  case "set_notes_value":
150
- this.notesInput.setValue(effect.value);
169
+ this.notesInput.setText(effect.value);
151
170
  return;
152
171
  case "set_notes_focused":
153
172
  this.notesInput.focused = effect.focused;
@@ -167,17 +186,10 @@ export class QuestionnaireSession {
167
186
  }
168
187
 
169
188
  /**
170
- * Per-keystroke `ignore` fast path: delegates to the headless `inlineInput`
171
- * Input so bracketed-paste accumulator (`input.js:33-63`) and Kitty CSI-u
172
- * decode (`input.js:155-163`) take effect. Cursor is NOT force-reset here —
173
- * doing so would corrupt split-chunk pastes (a `\x05` byte mid-paste lands
174
- * verbatim in `pasteBuffer` and survives `handlePaste`'s narrow strip).
175
- * Cursor advances naturally via `insertCharacter` on typing/paste; cursor-
176
- * movement keys (Left/Right/Home/End/word-jumps) are now functional, with
177
- * the always-end visual cursor marker drawn independently by
178
- * `WrappingSelect.renderInlineInputRow`. `viewAdapter.apply` is called
179
- * directly without a reducer round-trip — preserves the D3 fast-path
180
- * latency profile from Phase 11.
189
+ * Per-keystroke `ignore` fast path: delegates text editing to Pi's headless
190
+ * multiline `Editor`, including paste, undo, cursor movement, and configured
191
+ * `tui.input.newLine` handling. `viewAdapter.apply` then projects its public
192
+ * text/cursor state without a reducer round-trip.
181
193
  */
182
194
  private handleIgnoreInline(data: string): void {
183
195
  if (!this.state.inputMode) return;
@@ -186,9 +198,13 @@ export class QuestionnaireSession {
186
198
  }
187
199
 
188
200
  private runtime(): QuestionnaireRuntime {
201
+ const cursor = this.inlineInput.getCursor();
202
+ const lastLine = this.inlineInput.getLines().length - 1;
189
203
  return {
190
- keybindings: getKeybindings(),
191
- inputBuffer: this.inlineInput.getValue(),
204
+ keybindings: this.keybindings,
205
+ inputBuffer: this.inlineInput.getText(),
206
+ canMoveInputUp: cursor.line > 0,
207
+ canMoveInputDown: cursor.line < lastLine,
192
208
  questions: this.questions,
193
209
  isMulti: this.isMulti,
194
210
  currentItem: this.currentItem(),
@@ -227,6 +243,6 @@ export class QuestionnaireSession {
227
243
  * happens via the `set_overlay_hidden` effect like every other side effect.
228
244
  */
229
245
  toggleCollapsedExternal(): void {
230
- this.commit({ kind: "toggle_collapsed" });
246
+ if (!this.inputEditorOpen) this.commit({ kind: "toggle_collapsed" });
231
247
  }
232
248
  }
@@ -19,6 +19,7 @@ export interface ApplyContext {
19
19
  export type Effect =
20
20
  | { kind: "set_input_buffer"; value: string }
21
21
  | { kind: "clear_input_buffer" }
22
+ | { kind: "open_input_editor"; value: string }
22
23
  | { kind: "set_notes_value"; value: string }
23
24
  | { kind: "set_notes_focused"; focused: boolean }
24
25
  | { kind: "forward_notes_keystroke"; data: string }
@@ -95,6 +96,26 @@ function notesValueFor(state: QuestionnaireState, tab: number): string {
95
96
  return state.notesByTab.get(tab) ?? state.answers.get(tab)?.notes ?? "";
96
97
  }
97
98
 
99
+ function customDraftValueFor(state: QuestionnaireState, tab: number): string {
100
+ const draft = state.customDraftsByTab.get(tab);
101
+ if (draft !== undefined) return draft;
102
+ const answer = state.answers.get(tab);
103
+ return answer?.kind === "custom" && typeof answer.answer === "string" ? answer.answer : "";
104
+ }
105
+
106
+ function setCustomDraft(state: QuestionnaireState, tab: number, value: string): ReadonlyMap<number, string> {
107
+ const drafts = new Map(state.customDraftsByTab);
108
+ drafts.set(tab, value);
109
+ return drafts;
110
+ }
111
+
112
+ function withoutCustomDraft(state: QuestionnaireState, tab: number): ReadonlyMap<number, string> {
113
+ if (!state.customDraftsByTab.has(tab)) return state.customDraftsByTab;
114
+ const drafts = new Map(state.customDraftsByTab);
115
+ drafts.delete(tab);
116
+ return drafts;
117
+ }
118
+
98
119
  function switchTabResult(state: QuestionnaireState, nextTab: number, ctx: ApplyContext): ApplyResult {
99
120
  const notesValue = notesValueFor(state, nextTab);
100
121
  const transitioned: QuestionnaireState = {
@@ -112,6 +133,7 @@ function switchTabResult(state: QuestionnaireState, nextTab: number, ctx: ApplyC
112
133
  effects: [
113
134
  { kind: "set_notes_focused", focused: false },
114
135
  { kind: "set_notes_value", value: notesValue },
136
+ { kind: "set_input_buffer", value: customDraftValueFor(state, nextTab) },
115
137
  ],
116
138
  };
117
139
  }
@@ -135,17 +157,30 @@ const navHandler: Handler<"nav"> = (state, action, ctx) => {
135
157
  const items = ctx.itemsByTab[state.currentTab] ?? [];
136
158
  const item = items[action.nextIndex];
137
159
  const inputMode = item ? ROW_INTENT_META[item.kind].activatesInputMode : false;
138
- const next = { ...state, optionIndex: action.nextIndex, inputMode };
139
- if (!inputMode) {
140
- return { state: next, effects: [{ kind: "clear_input_buffer" }] };
141
- }
142
- const prior = state.answers.get(state.currentTab);
143
- if (prior?.kind === "custom" && typeof prior.answer === "string") {
144
- return { state: next, effects: [{ kind: "set_input_buffer", value: prior.answer }] };
145
- }
146
- return { state: next, effects: [] };
160
+ const customDraftsByTab = state.inputMode
161
+ ? setCustomDraft(state, state.currentTab, action.inputValue)
162
+ : state.customDraftsByTab;
163
+ const next: QuestionnaireState = { ...state, optionIndex: action.nextIndex, inputMode, customDraftsByTab };
164
+ if (!inputMode) return { state: next, effects: [] };
165
+ return {
166
+ state: next,
167
+ effects: [{ kind: "set_input_buffer", value: customDraftValueFor(next, state.currentTab) }],
168
+ };
147
169
  };
148
170
 
171
+ const inputClearHandler: Handler<"input_clear"> = (state, _action, _ctx) => ({
172
+ state: { ...state, customDraftsByTab: setCustomDraft(state, state.currentTab, "") },
173
+ effects: [{ kind: "clear_input_buffer" }],
174
+ });
175
+ const inputEditHandler: Handler<"input_edit"> = (state, action, _ctx) => ({
176
+ state,
177
+ effects: [{ kind: "open_input_editor", value: action.value }],
178
+ });
179
+ const inputReplaceHandler: Handler<"input_replace"> = (state, action, _ctx) => ({
180
+ state: { ...state, customDraftsByTab: setCustomDraft(state, state.currentTab, action.value) },
181
+ effects: [{ kind: "set_input_buffer", value: action.value }],
182
+ });
183
+
149
184
  const tabSwitchHandler: Handler<"tab_switch"> = (state, action, ctx) => switchTabResult(state, action.nextTab, ctx);
150
185
 
151
186
  const confirmHandler: Handler<"confirm"> = (state, action, ctx) => {
@@ -167,9 +202,12 @@ const confirmHandler: Handler<"confirm"> = (state, action, ctx) => {
167
202
  // clear the checked set immediately so [✔] glyphs vanish on Enter. (A custom answer
168
203
  // carries no `selected` array, so syncMultiSelectFromAnswers keeps it empty on tab-back.)
169
204
  const isCustomMulti = answer.kind === "custom" && ctx.questions[answer.questionIndex]?.multiSelect === true;
205
+ const customDraftsByTab =
206
+ answer.kind === "custom" ? withoutCustomDraft(state, answer.questionIndex) : state.customDraftsByTab;
170
207
  const next: QuestionnaireState = {
171
208
  ...state,
172
209
  answers,
210
+ customDraftsByTab,
173
211
  ...(isCustomMulti ? { multiSelectChecked: new Set<number>() } : {}),
174
212
  };
175
213
  if (action.autoAdvanceTab !== undefined) return switchTabResult(next, action.autoAdvanceTab, ctx);
@@ -265,6 +303,9 @@ const ignoreHandler: Handler<"ignore"> = (s, _a, _c) => ({ state: s, effects: []
265
303
  */
266
304
  const HANDLERS: { [K in QuestionnaireAction["kind"]]: Handler<K> } = {
267
305
  nav: navHandler,
306
+ input_clear: inputClearHandler,
307
+ input_edit: inputEditHandler,
308
+ input_replace: inputReplaceHandler,
268
309
  tab_switch: tabSwitchHandler,
269
310
  confirm: confirmHandler,
270
311
  toggle: toggleHandler,
package/state/state.ts CHANGED
@@ -12,6 +12,8 @@ export interface QuestionnaireState {
12
12
  notesVisible: boolean;
13
13
  answers: ReadonlyMap<number, QuestionAnswer>;
14
14
  multiSelectChecked: ReadonlySet<number>;
15
+ /** In-flight custom answers keyed by tab. A present empty string overrides an older answer. */
16
+ customDraftsByTab: ReadonlyMap<number, string>;
15
17
  /**
16
18
  * Pre-answer notes side-band, keyed by tab index. Decoupled from `answers` so adding
17
19
  * notes does NOT mark a question answered (the Submit-tab missing-check would falsely
@@ -40,6 +42,8 @@ export interface QuestionnaireState {
40
42
  export interface QuestionnaireRuntime {
41
43
  keybindings: { matches(data: string, name: string): boolean };
42
44
  inputBuffer: string;
45
+ canMoveInputUp: boolean;
46
+ canMoveInputDown: boolean;
43
47
  questions: readonly QuestionData[];
44
48
  isMulti: boolean;
45
49
  currentItem: WrappingSelectItem | undefined;
@@ -1,11 +1,10 @@
1
- import { CURSOR_MARKER, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
1
+ import { CURSOR_MARKER, wrapTextWithAnsi } from "@earendil-works/pi-tui";
2
2
 
3
- // Grapheme-aware extraction at the cursor: pi-tui's Input advances `cursor` by
4
- // grapheme-cluster code-unit length, so the cursor can land between code units of
5
- // one cluster (emoji, ZWJ, combining marks). Single-code-unit slicing would split
6
- // the cluster across the SGR 7/27 boundary. Moved here from wrapping-select.ts so
7
- // both the single-select (wrap) and multi-select (truncate-to-one-line) inline
8
- // inputs share one cursor-building core.
3
+ // Grapheme-aware extraction at the cursor: pi-tui's Editor reports UTF-16
4
+ // line/column positions, so the cursor can land between code units of one cluster
5
+ // (emoji, ZWJ, combining marks). Single-code-unit slicing would split the cluster
6
+ // across the SGR 7/27 boundary. Both single- and multi-select views share this
7
+ // cursor-building core.
9
8
  const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
10
9
 
11
10
  export interface RenderInlineInputOptions {
@@ -21,15 +20,6 @@ export interface RenderInlineInputOptions {
21
20
  contentWidth: number;
22
21
  /** Per-line styling (single-select: `theme.selectedText`; multi-select: accent+bold). */
23
22
  selectedText: (text: string) => string;
24
- /**
25
- * `true` (single-select): wrap across lines at `contentWidth` (byte-identical to the
26
- * pre-extraction wrapping-select behavior).
27
- * `false` (multi-select): collapse to ONE line — truncate the plain buffer to
28
- * `contentWidth` with `…` when the cursor-marked content would overflow, keeping the
29
- * dialog height state-independent. The cursor is clipped past the visible window
30
- * (accepted trade): when the cursor-marked content fits it is rendered in full.
31
- */
32
- multiline: boolean;
33
23
  }
34
24
 
35
25
  /**
@@ -53,44 +43,24 @@ function buildCursorRaw(buffer: string, offset: number): string {
53
43
  const before = buffer.slice(0, offset);
54
44
  const [firstGrapheme] = graphemeSegmenter.segment(buffer.slice(offset));
55
45
  const rawAt = firstGrapheme ? firstGrapheme.segment : "";
56
- // NBSP (U+00A0) fallback: visually identical to a space, wrap-safe.
57
- const atCursor = rawAt === "" || rawAt === " " ? "\xa0" : rawAt;
58
- const after = buffer.slice(offset + rawAt.length);
46
+ // A logical newline has no visible cell. Draw the cursor on an NBSP immediately
47
+ // before it and leave the newline unconsumed so the next logical line still renders.
48
+ const cursorAtLineEnd = rawAt === "\n";
49
+ const atCursor = rawAt === "" || rawAt === " " || cursorAtLineEnd ? "\xa0" : rawAt;
50
+ const after = buffer.slice(offset + (cursorAtLineEnd ? 0 : rawAt.length));
59
51
  return `${before}${CURSOR_MARKER}\x1b[7m${atCursor}\x1b[27m${after}`;
60
52
  }
61
53
 
62
54
  /**
63
- * Render the inline-input row. `multiline: true` wraps (single-select, byte-identical to
64
- * the pre-extraction output); `multiline: false` collapses to a single line.
65
- *
66
- * Cursor visualization follows the standard TUI input-widget pattern (ECMA-48 SGR 7
67
- * reverse-video on the cell AT the cursor, not an inserted glyph) — same approach used by
68
- * pi-tui Input.render, ink-text-input, terkelg/prompts, ratatui's user-input example.
55
+ * Render the inline editor across logical and visually wrapped lines.
56
+ * Cursor visualization follows Pi's editor pattern: reverse-video on the cell at
57
+ * the cursor, with a non-breaking-space cell at end-of-line/end-of-buffer.
69
58
  */
70
59
  export function renderInlineInputRow(opts: RenderInlineInputOptions): string[] {
71
- const { buffer, cursorOffset, rowPrefix, continuationPrefix, contentWidth, selectedText, multiline } = opts;
72
- const offset = resolveCursorOffset(buffer, cursorOffset);
73
-
74
- if (multiline) {
75
- // Single-select: wrap at contentWidth. Byte-identical to the original
76
- // wrapping-select.renderInlineInputRow output (same raw, same wrapTextWithAnsi,
77
- // same prefix/selectedText per line).
78
- const raw = buildCursorRaw(buffer, offset);
79
- const wrapped = wrapTextWithAnsi(raw, contentWidth);
80
- return wrapped.map((segment, index) => {
81
- const prefix = index === 0 ? rowPrefix : continuationPrefix;
82
- return selectedText(`${prefix}${segment}`);
83
- });
84
- }
85
-
86
- // Multi-select: single line. Build the cursor markup on the full buffer; if it fits
87
- // contentWidth, emit it as one line. If it overflows, fall back to truncating the PLAIN
88
- // buffer (ANSI-safe — never cut a CURSOR_MARKER/SGR sequence) with `…` and clip the
89
- // cursor. This keeps the row at exactly one line so naturalHeight stays state-independent.
90
- const cursorRaw = buildCursorRaw(buffer, offset);
91
- if (visibleWidth(cursorRaw) <= contentWidth) {
92
- return [selectedText(`${rowPrefix}${cursorRaw}`)];
93
- }
94
- const clipped = truncateToWidth(buffer, contentWidth, "…");
95
- return [selectedText(`${rowPrefix}${clipped}`)];
60
+ const { buffer, cursorOffset, rowPrefix, continuationPrefix, contentWidth, selectedText } = opts;
61
+ const raw = buildCursorRaw(buffer, resolveCursorOffset(buffer, cursorOffset));
62
+ return wrapTextWithAnsi(raw, contentWidth).map((segment, index) => {
63
+ const prefix = index === 0 ? rowPrefix : continuationPrefix;
64
+ return selectedText(`${prefix}${segment}`);
65
+ });
96
66
  }
@@ -38,14 +38,21 @@ export interface MultiSelectViewProps {
38
38
  * Renders the multi-select option list (one row per option — pointer + checkbox + label —
39
39
  * plus zero or more wrapped continuation lines per description).
40
40
  *
41
- * `naturalHeight(width)` is state-INDEPENDENT (depends only on theme glyph widths,
42
- * question.options, and width) so the host can compute a stable globalContentHeight
43
- * without rendering. `naturalHeight(w) === render(w).length` for every props.
41
+ * `naturalHeight(width)` is the rendered height for the current props. It grows when
42
+ * the custom-answer editor contains logical or visually wrapped lines, allowing the
43
+ * dialog to reserve exactly the space the active draft needs.
44
44
  *
45
- * `setProps(props)` is a pure field reassignment — no render, no invalidate side effects.
45
+ * One width-keyed layout supplies rendering, height, and focused-row measurement;
46
+ * `setProps` and `invalidate` discard that derived cache.
46
47
  */
48
+ interface MultiSelectLayout {
49
+ lines: string[];
50
+ focusedRange: [number, number];
51
+ }
52
+
47
53
  export class MultiSelectView implements StatefulView<MultiSelectViewProps> {
48
54
  private props: MultiSelectViewProps;
55
+ private cachedLayout: { width: number; value: MultiSelectLayout } | undefined;
49
56
 
50
57
  constructor(
51
58
  private readonly theme: Theme,
@@ -61,118 +68,97 @@ export class MultiSelectView implements StatefulView<MultiSelectViewProps> {
61
68
 
62
69
  setProps(props: MultiSelectViewProps): void {
63
70
  this.props = props;
71
+ this.cachedLayout = undefined;
64
72
  }
65
73
 
66
74
  handleInput(_data: string): void {}
67
75
 
68
- invalidate(): void {}
76
+ invalidate(): void {
77
+ this.cachedLayout = undefined;
78
+ }
69
79
 
70
80
  render(width: number): string[] {
81
+ return this.layout(width).lines;
82
+ }
83
+
84
+ focusedItemRowRange(width: number): [number, number] {
85
+ return this.layout(width).focusedRange;
86
+ }
87
+
88
+ naturalHeight(width: number): number {
89
+ return this.layout(width).lines.length;
90
+ }
91
+
92
+ private layout(width: number): MultiSelectLayout {
93
+ if (this.cachedLayout?.width === width) return this.cachedLayout.value;
94
+
71
95
  const lines: string[] = [];
72
- const prefixWidth = this.prefixVisibleWidth();
73
- const contentWidth = Math.max(1, width - prefixWidth);
96
+ let focusedRange: [number, number] = [0, 0];
97
+ const contentWidth = Math.max(1, width - this.prefixVisibleWidth());
74
98
  const numberWidth = String(Math.max(1, this.question.options.length + 1)).length;
75
99
  for (let i = 0; i < this.question.options.length; i++) {
76
100
  const opt = this.question.options[i];
77
101
  const row = this.props.rows[i];
78
102
  if (!opt || !row) continue;
103
+ const start = lines.length;
79
104
  const pointer = row.active ? this.theme.fg("accent", ACTIVE_POINTER) : INACTIVE_POINTER;
80
- // Checked uses the same `accent` hue as the active-row label so checked rows read
81
- // as "selected" rather than "success" — matches the visual rhythm of the rest of
82
- // the dialog (active pointer, label, picker rows are all accent).
105
+ // Checked and active rows share the accent hue, matching the dialog's selection rhythm.
83
106
  const box = row.checked ? this.theme.fg("accent", CHECKED) : this.theme.fg("muted", UNCHECKED);
84
107
  const label = truncateToWidth(opt.label, contentWidth, "…");
85
108
  const styledLabel = row.active ? this.theme.fg("accent", this.theme.bold(label)) : label;
86
- const num = String(i + 1).padStart(numberWidth, " ");
87
- const line = `${pointer}${num}${NUMBER_SEPARATOR}${box}${BOX_LABEL_GAP}${styledLabel}`;
88
- lines.push(truncateToWidth(line, width, ""));
109
+ const number = String(i + 1).padStart(numberWidth, " ");
110
+ lines.push(
111
+ truncateToWidth(`${pointer}${number}${NUMBER_SEPARATOR}${box}${BOX_LABEL_GAP}${styledLabel}`, width, ""),
112
+ );
89
113
  if (opt.description) {
90
- const wrapped = wrapTextWithAnsi(opt.description, contentWidth);
91
- for (const segment of wrapped) {
114
+ for (const segment of wrapTextWithAnsi(opt.description, contentWidth)) {
92
115
  lines.push(CONTINUATION_INDENT + this.theme.fg("muted", segment));
93
116
  }
94
117
  }
118
+ if (row.active) focusedRange = [start, lines.length];
95
119
  }
96
120
 
97
- // "Type something." row — numbered N+1, box always [ ] muted UNCHECKED (never checkable).
98
- // When focused + inputMode, render the label slot via the shared inline-input helper
99
- // (single-line); otherwise a static localized label truncated to contentWidth with `…`.
100
- const other = this.props.other;
101
- const otherPointer = other.active ? this.theme.fg("accent", ACTIVE_POINTER) : INACTIVE_POINTER;
102
- const otherBox = this.theme.fg("muted", UNCHECKED);
103
- const otherNum = String(this.question.options.length + 1).padStart(numberWidth, " ");
104
- let otherLabel: string;
105
- if (other.active && other.inputMode) {
106
- const rendered = renderInlineInputRow({
107
- buffer: other.inputBuffer,
108
- cursorOffset: other.inputCursorOffset,
109
- rowPrefix: "",
110
- continuationPrefix: "",
111
- contentWidth,
112
- selectedText: (t) => this.theme.fg("accent", this.theme.bold(t)),
113
- multiline: false,
114
- });
115
- otherLabel = rendered[0] ?? "";
116
- } else {
117
- const label = truncateToWidth(displayLabel("other"), contentWidth, "…");
118
- otherLabel = other.active ? this.theme.fg("accent", this.theme.bold(label)) : label;
119
- }
120
- lines.push(
121
- truncateToWidth(
122
- `${otherPointer}${otherNum}${NUMBER_SEPARATOR}${otherBox}${BOX_LABEL_GAP}${otherLabel}`,
123
- width,
124
- "",
125
- ),
126
- );
121
+ const otherStart = lines.length;
122
+ lines.push(...this.renderOtherRow(contentWidth, numberWidth));
123
+ if (this.props.other.active) focusedRange = [otherStart, lines.length];
127
124
 
125
+ const nextStart = lines.length;
128
126
  const nextPointer = this.props.nextActive ? this.theme.fg("accent", ACTIVE_POINTER) : INACTIVE_POINTER;
129
127
  const nextLabel = this.props.nextActive
130
128
  ? this.theme.fg("accent", this.theme.bold(this.props.nextLabel))
131
129
  : this.props.nextLabel;
132
130
  lines.push(truncateToWidth(`${nextPointer}${nextLabel}`, width, ""));
133
- return lines;
134
- }
131
+ if (this.props.nextActive) focusedRange = [nextStart, lines.length];
135
132
 
136
- /**
137
- * Returns the [startRow, endRow) range of the active (focused) row within
138
- * `render(width)`. Labels are always 1 row (truncated); descriptions wrap.
139
- */
140
- focusedItemRowRange(width: number): [number, number] {
141
- const prefixWidth = this.prefixVisibleWidth();
142
- const contentWidth = Math.max(1, width - prefixWidth);
143
- let row = 0;
144
- for (let i = 0; i < this.question.options.length; i++) {
145
- const opt = this.question.options[i];
146
- const r = this.props.rows[i];
147
- if (!opt || !r) continue;
148
- const itemHeight = 1 + (opt.description ? wrapTextWithAnsi(opt.description, contentWidth).length : 0);
149
- if (r.active) {
150
- return [row, row + itemHeight];
151
- }
152
- row += itemHeight;
153
- }
154
- // "Type something." row is always exactly 1 line (truncated, no description).
155
- if (this.props.other.active) {
156
- return [row, row + 1];
157
- }
158
- row += 1;
159
- if (this.props.nextActive) {
160
- return [row, row + 1];
161
- }
162
- return [0, 0];
133
+ const value = { lines, focusedRange };
134
+ this.cachedLayout = { width, value };
135
+ return value;
163
136
  }
164
137
 
165
- naturalHeight(width: number): number {
166
- const contentWidth = Math.max(1, width - this.prefixVisibleWidth());
167
- let total = 0;
168
- for (const opt of this.question.options) {
169
- if (!opt) continue;
170
- total += 1; // row line
171
- if (opt.description) {
172
- total += wrapTextWithAnsi(opt.description, contentWidth).length;
173
- }
138
+ private renderOtherRow(contentWidth: number, numberWidth: number): string[] {
139
+ const other = this.props.other;
140
+ const pointer = other.active ? this.theme.fg("accent", ACTIVE_POINTER) : INACTIVE_POINTER;
141
+ const box = this.theme.fg("muted", UNCHECKED);
142
+ const number = String(this.question.options.length + 1).padStart(numberWidth, " ");
143
+ const rowPrefix = `${pointer}${number}${NUMBER_SEPARATOR}${box}${BOX_LABEL_GAP}`;
144
+ const continuationPrefix = " ".repeat(visibleWidth(rowPrefix));
145
+ const selectedText = (text: string) => this.theme.fg("accent", this.theme.bold(text));
146
+
147
+ if (other.active && other.inputMode) {
148
+ return renderInlineInputRow({
149
+ buffer: other.inputBuffer,
150
+ cursorOffset: other.inputCursorOffset,
151
+ rowPrefix,
152
+ continuationPrefix,
153
+ contentWidth,
154
+ selectedText,
155
+ });
174
156
  }
175
- return total + 2; // "Type something." row + Next sentinel row (neither wraps).
157
+
158
+ return wrapTextWithAnsi(other.inputBuffer || displayLabel("other"), contentWidth).map((segment, index) => {
159
+ const line = `${index === 0 ? rowPrefix : continuationPrefix}${segment}`;
160
+ return other.active ? selectedText(line) : line;
161
+ });
176
162
  }
177
163
 
178
164
  private prefixVisibleWidth(): number {
@@ -15,7 +15,7 @@ export interface OptionListViewConfig {
15
15
  /**
16
16
  * Per-tick projection of OptionListView state. After Phase 11b, `inputBuffer`
17
17
  * is part of the props bag — the session-owned `inlineInput` (a headless
18
- * `pi-tui` Input instance) supplies its current `getValue()` here per tick.
18
+ * `pi-tui` Editor instance) supplies its current `getText()` here per tick.
19
19
  * `OptionListView` is purely props-driven; the imperative buffer surface and
20
20
  * read-back getters are gone.
21
21
  */
@@ -12,7 +12,7 @@ import { renderInlineInputRow } from "./inline-input.js";
12
12
  * Variant semantics:
13
13
  * - `option`: a regular author-defined option row.
14
14
  * - `other`: the inline free-text input row appended to every question
15
- * (label is "Type something."). Renders as inline `Input` when active.
15
+ * (label is "Type something."). Renders the headless multiline editor when active.
16
16
  * - `next`: the explicit commit-and-advance row appended to multi-select questions
17
17
  * (label is "Next"). Renders without a number / checkbox.
18
18
  */
@@ -216,16 +216,20 @@ export class WrappingSelect implements Component {
216
216
  return this.renderInlineInputRow(rowPrefix, continuationPrefix, contentWidth);
217
217
  }
218
218
 
219
- // Confirmed row gets a trailing ` ✔` and accent+bold styling; pointer is independent
220
- // (still ❯ when active). When `index === confirmedIndex` AND `isActive`, both `❯` and
221
- // `✔` appear on the same row — load-bearing for the case where the prior answer was
222
- // row 0 (cursor resets to 0 on tab-back, so the confirmed row IS the active row).
223
- // Optional `confirmedLabelOverride` replaces the static label (used for `kind: "other"`
224
- // + `kind: "custom"` answer); the inline-input branch above still wins for `kind: "other" + isActive`.
225
- const isConfirmed = index === this.confirmedIndex;
219
+ // Keep an in-flight custom draft visible even while the cursor browses another row.
220
+ // If it differs from a previously confirmed custom answer, omit the confirmation
221
+ // mark so the pending draft is not presented as committed.
222
+ const customDraft = item.kind === "other" ? this.inputBuffer : undefined;
223
+ const customDraftDiffersFromConfirmed =
224
+ item.kind === "other" &&
225
+ customDraft !== "" &&
226
+ index === this.confirmedIndex &&
227
+ customDraft !== (this.confirmedLabelOverride ?? "");
228
+ const isConfirmed = index === this.confirmedIndex && !customDraftDiffersFromConfirmed;
229
+ const baseLabel = customDraft ? customDraft : item.label;
226
230
  const label = isConfirmed
227
- ? `${this.confirmedLabelOverride ?? item.label}${WrappingSelect.CONFIRMED_MARK}`
228
- : item.label;
231
+ ? `${this.confirmedLabelOverride ?? baseLabel}${WrappingSelect.CONFIRMED_MARK}`
232
+ : baseLabel;
229
233
  const applySelectedStyle = isActive || isConfirmed;
230
234
 
231
235
  return [
@@ -245,13 +249,7 @@ export class WrappingSelect implements Component {
245
249
  return item.kind === "other" && isActive;
246
250
  }
247
251
 
248
- /**
249
- * Render the inline input row across one or more lines, wrapping at `contentWidth`.
250
- * Delegates to the shared `renderInlineInputRow` helper (`./inline-input.ts`) so the
251
- * single-select wrap path and the multi-select single-line path share one cursor-
252
- * building core. The `multiline: true` path is byte-identical to the pre-extraction
253
- * output (cursor rationale lives in `inline-input.ts`).
254
- */
252
+ /** Render the inline editor across logical and visually wrapped lines. */
255
253
  private renderInlineInputRow(rowPrefix: string, continuationPrefix: string, contentWidth: number): string[] {
256
254
  return renderInlineInputRow({
257
255
  buffer: this.inputBuffer,
@@ -260,7 +258,6 @@ export class WrappingSelect implements Component {
260
258
  continuationPrefix,
261
259
  contentWidth,
262
260
  selectedText: this.theme.selectedText,
263
- multiline: true,
264
261
  });
265
262
  }
266
263