@juicesharp/rpiv-ask-user-question 2.0.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.
@@ -7,12 +7,20 @@ const KEYBIND_UP = "tui.select.up";
7
7
  const KEYBIND_DOWN = "tui.select.down";
8
8
  const KEYBIND_CONFIRM = "tui.select.confirm";
9
9
  const KEYBIND_CANCEL = "tui.select.cancel";
10
+ const KEYBIND_NEW_LINE = "tui.input.newLine";
11
+ const KEYBIND_EDITOR_UP = "tui.editor.cursorUp";
12
+ const KEYBIND_EDITOR_DOWN = "tui.editor.cursorDown";
13
+ const KEYBIND_CLEAR = "tui.editor.deleteToLineStart";
14
+ const KEYBIND_EXTERNAL_EDITOR = "app.editor.external";
10
15
 
11
16
  const NOTES_ACTIVATE_KEY = "n";
12
17
  const SPACE_KEY = " ";
13
18
 
14
19
  export type QuestionnaireAction =
15
- | { kind: "nav"; nextIndex: number }
20
+ | { kind: "nav"; nextIndex: number; inputValue: string }
21
+ | { kind: "input_clear" }
22
+ | { kind: "input_edit"; value: string }
23
+ | { kind: "input_replace"; value: string }
16
24
  | { kind: "tab_switch"; nextTab: number }
17
25
  | { kind: "confirm"; answer: QuestionAnswer; autoAdvanceTab?: number }
18
26
  | { kind: "toggle"; index: number }
@@ -115,12 +123,20 @@ function tabSwitchAction(
115
123
 
116
124
  // DOWN at the last item wraps to the first (cycle through [option0, …, optionLast]).
117
125
  function nextNavOnDown(state: QuestionnaireState, runtime: QuestionnaireRuntime): QuestionnaireAction {
118
- return { kind: "nav", nextIndex: wrapTab(state.optionIndex + 1, Math.max(1, runtime.items.length)) };
126
+ return {
127
+ kind: "nav",
128
+ nextIndex: wrapTab(state.optionIndex + 1, Math.max(1, runtime.items.length)),
129
+ inputValue: runtime.inputBuffer,
130
+ };
119
131
  }
120
132
 
121
133
  // UP at the first item wraps to the last (symmetric with nextNavOnDown).
122
134
  function prevNavOnUp(state: QuestionnaireState, runtime: QuestionnaireRuntime): QuestionnaireAction {
123
- return { kind: "nav", nextIndex: wrapTab(state.optionIndex - 1, Math.max(1, runtime.items.length)) };
135
+ return {
136
+ kind: "nav",
137
+ nextIndex: wrapTab(state.optionIndex - 1, Math.max(1, runtime.items.length)),
138
+ inputValue: runtime.inputBuffer,
139
+ };
124
140
  }
125
141
 
126
142
  export function routeKey(data: string, state: QuestionnaireState, runtime: QuestionnaireRuntime): QuestionnaireAction {
@@ -142,7 +158,17 @@ export function routeKey(data: string, state: QuestionnaireState, runtime: Quest
142
158
  // in-process. It is, however, awkward on keyboard layouts where `]` is on the
143
159
  // shifted layer (Latin American `es-AR`/`es-MX` require `Ctrl+Shift+}` for `Ctrl+]`)
144
160
  // — use the `collapseKey` config field to override.
145
- if (runtime.collapseKey !== "off" && matchesKey(data, runtime.collapseKey as Parameters<typeof matchesKey>[1])) {
161
+ // Treat a missing/non-string key as disabled. This can occur at runtime when
162
+ // a long-lived Pi process retains an older outer module while a package update
163
+ // replaces the lazily imported QuestionnaireSession graph on disk. Passing
164
+ // undefined into matchesKey reaches parseKeyId().toLowerCase() and crashes the
165
+ // entire host process, so keep the runtime boundary defensive even though the
166
+ // TypeScript contract requires a string.
167
+ if (
168
+ typeof runtime.collapseKey === "string" &&
169
+ runtime.collapseKey !== "off" &&
170
+ matchesKey(data, runtime.collapseKey as Parameters<typeof matchesKey>[1])
171
+ ) {
146
172
  return { kind: "toggle_collapsed" };
147
173
  }
148
174
 
@@ -156,23 +182,31 @@ export function routeKey(data: string, state: QuestionnaireState, runtime: Quest
156
182
 
157
183
  if (state.notesVisible) {
158
184
  if (kb.matches(data, KEYBIND_CANCEL)) return { kind: "notes_exit" };
185
+ if (kb.matches(data, KEYBIND_NEW_LINE)) return { kind: "notes_forward", data };
159
186
  if (kb.matches(data, KEYBIND_CONFIRM)) return { kind: "notes_exit" };
160
187
  return { kind: "notes_forward", data };
161
188
  }
162
189
 
163
190
  if (state.inputMode) {
191
+ // Newline takes precedence over confirmation if a user configuration binds
192
+ // the same physical key to both semantic actions.
193
+ if (kb.matches(data, KEYBIND_NEW_LINE)) return { kind: "ignore" };
164
194
  if (kb.matches(data, KEYBIND_CONFIRM)) {
165
195
  const answer = buildSingleSelectAnswer(state, runtime);
166
196
  if (!answer) return { kind: "ignore" };
167
197
  return { kind: "confirm", answer, autoAdvanceTab: computeAutoAdvanceTab(state, runtime) };
168
198
  }
199
+ // Treat Pi's Ctrl+U line-kill binding as an explicit whole-draft clear,
200
+ // independent of the current cursor position.
201
+ if (kb.matches(data, KEYBIND_CLEAR)) return { kind: "input_clear" };
202
+ if (kb.matches(data, KEYBIND_EXTERNAL_EDITOR)) return { kind: "input_edit", value: runtime.inputBuffer };
169
203
  if (kb.matches(data, KEYBIND_CANCEL)) return { kind: "cancel" };
170
- if (kb.matches(data, KEYBIND_UP)) {
171
- return prevNavOnUp(state, runtime);
172
- }
173
- if (kb.matches(data, KEYBIND_DOWN)) {
174
- return nextNavOnDown(state, runtime);
204
+ if (kb.matches(data, KEYBIND_EDITOR_UP) && runtime.canMoveInputUp) return { kind: "ignore" };
205
+ if (kb.matches(data, KEYBIND_EDITOR_DOWN) && runtime.canMoveInputDown) {
206
+ return { kind: "ignore" };
175
207
  }
208
+ if (kb.matches(data, KEYBIND_UP)) return prevNavOnUp(state, runtime);
209
+ if (kb.matches(data, KEYBIND_DOWN)) return nextNavOnDown(state, runtime);
176
210
  return { kind: "ignore" };
177
211
  }
178
212
 
@@ -200,7 +234,16 @@ export function routeKey(data: string, state: QuestionnaireState, runtime: Quest
200
234
  const q = runtime.questions[state.currentTab];
201
235
  if (!q) return { kind: "ignore" };
202
236
 
203
- if (data === NOTES_ACTIVATE_KEY && !q.multiSelect && state.focusedOptionHasPreview) {
237
+ // Universal `n` activation (FR-1): the notes editor opens on every question tab
238
+ // (single- or multi-select, preview or no-preview). The blocks above already
239
+ // swallow `n` when it should NOT reach here — notesVisible forwards to the
240
+ // notes Input, inputMode forwards to the inline Input, the submit-tab block
241
+ // ignores it, and tabSwitchAction ignores it — so by the time we reach this
242
+ // gate, `n` is unambiguously a notes-enter request. Row intent (Next sentinel,
243
+ // "Type something.") is irrelevant: the gate sits ABOVE the multi-select
244
+ // toggle block and the Next sentinel never activates inputMode, so `n` is
245
+ // neither swallowed earlier nor blocked by `blocksMultiToggle`.
246
+ if (data === NOTES_ACTIVATE_KEY) {
204
247
  return { kind: "notes_enter" };
205
248
  }
206
249
 
@@ -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";
@@ -7,20 +7,18 @@ import type { QuestionnairePropsAdapter } from "../view/props-adapter.js";
7
7
  import { buildQuestionnaire } from "./build-questionnaire.js";
8
8
  import { t } from "./i18n-bridge.js";
9
9
  import { type QuestionnaireAction, routeKey } from "./key-router.js";
10
- import { computeFocusedOptionHasPreview } from "./selectors/derivations.js";
11
10
  import type { QuestionnaireRuntime, QuestionnaireState } from "./state.js";
12
11
  import { type ApplyContext, type Effect, reduce } from "./state-reducer.js";
13
12
 
14
- // Module-level constant; reused for cursor-end mutations after setValue rehydration.
15
- // Ctrl-E → tui.editor.cursorLineEnd (public path; pi-tui keybindings.js:25-28).
16
- const CURSOR_END = "\x05";
17
-
18
13
  export interface QuestionnaireSessionConfig {
19
- tui: { terminal: { columns: number; rows: number }; requestRender(): void };
14
+ tui: TUI;
20
15
  theme: Theme;
21
16
  params: QuestionParams;
22
17
  itemsByTab: WrappingSelectItem[][];
23
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>;
24
22
  /** Key spec for the collapse/expand shortcut, e.g. `"ctrl+]"` or `"alt+o"`. */
25
23
  collapseKey: string;
26
24
  }
@@ -39,8 +37,8 @@ function initialState(): QuestionnaireState {
39
37
  notesVisible: false,
40
38
  answers: new Map(),
41
39
  multiSelectChecked: new Set(),
40
+ customDraftsByTab: new Map(),
42
41
  notesByTab: new Map(),
43
- focusedOptionHasPreview: false,
44
42
  submitChoiceIndex: 0,
45
43
  notesDraft: "",
46
44
  collapsed: false,
@@ -48,8 +46,8 @@ function initialState(): QuestionnaireState {
48
46
  }
49
47
 
50
48
  /**
51
- * Slim runtime: owns the canonical state cell, the input-buffer cell, the
52
- * 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
53
51
  * transitions go through the pure `reduce` reducer; UI fan-out goes through
54
52
  * the `QuestionnairePropsAdapter` produced by `buildQuestionnaire`.
55
53
  */
@@ -60,10 +58,13 @@ export class QuestionnaireSession {
60
58
  private readonly isMulti: boolean;
61
59
  private readonly itemsByTab: WrappingSelectItem[][];
62
60
 
63
- private readonly notesInput: Input;
64
- private readonly inlineInput: Input;
61
+ private readonly notesInput: Editor;
62
+ private readonly inlineInput: Editor;
65
63
  private readonly viewAdapter: QuestionnairePropsAdapter;
64
+ private readonly keybindings: QuestionnaireRuntime["keybindings"];
65
+ private readonly editInput: QuestionnaireSessionConfig["editInput"];
66
66
  private readonly collapseKey: string;
67
+ private inputEditorOpen = false;
67
68
 
68
69
  /**
69
70
  * Overlay handle captured by `ctx.ui.custom`'s `onHandle` callback. Lets the session
@@ -82,9 +83,9 @@ export class QuestionnaireSession {
82
83
  this.questions = config.params.questions;
83
84
  this.isMulti = this.questions.length > 1;
84
85
  this.itemsByTab = config.itemsByTab;
86
+ this.keybindings = config.keybindings;
87
+ this.editInput = config.editInput;
85
88
  this.collapseKey = config.collapseKey;
86
- // Seed from the focused option at start; the reducer keeps it in sync via withFocusedOptionHasPreview.
87
- this.state = { ...this.state, focusedOptionHasPreview: computeFocusedOptionHasPreview(this.questions, 0, 0) };
88
89
 
89
90
  const built = buildQuestionnaire({
90
91
  tui: this.tui,
@@ -120,6 +121,7 @@ export class QuestionnaireSession {
120
121
  }
121
122
 
122
123
  dispatch(data: string): void {
124
+ if (this.inputEditorOpen) return;
123
125
  const action = routeKey(data, this.state, this.runtime());
124
126
  if (action.kind === "ignore") {
125
127
  this.handleIgnoreInline(data);
@@ -137,21 +139,34 @@ export class QuestionnaireSession {
137
139
  }
138
140
 
139
141
  private mirrorNotesDraft(s: QuestionnaireState): QuestionnaireState {
140
- const draft = this.notesInput.getValue();
142
+ const draft = this.notesInput.getText();
141
143
  return s.notesDraft === draft ? s : { ...s, notesDraft: draft };
142
144
  }
143
145
 
144
146
  private runEffect(effect: Effect): void {
145
147
  switch (effect.kind) {
146
148
  case "set_input_buffer":
147
- this.inlineInput.setValue(effect.value);
148
- this.inlineInput.handleInput(CURSOR_END);
149
+ this.inlineInput.setText(effect.value);
149
150
  return;
150
151
  case "clear_input_buffer":
151
- 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
+ );
152
167
  return;
153
168
  case "set_notes_value":
154
- this.notesInput.setValue(effect.value);
169
+ this.notesInput.setText(effect.value);
155
170
  return;
156
171
  case "set_notes_focused":
157
172
  this.notesInput.focused = effect.focused;
@@ -171,17 +186,10 @@ export class QuestionnaireSession {
171
186
  }
172
187
 
173
188
  /**
174
- * Per-keystroke `ignore` fast path: delegates to the headless `inlineInput`
175
- * Input so bracketed-paste accumulator (`input.js:33-63`) and Kitty CSI-u
176
- * decode (`input.js:155-163`) take effect. Cursor is NOT force-reset here —
177
- * doing so would corrupt split-chunk pastes (a `\x05` byte mid-paste lands
178
- * verbatim in `pasteBuffer` and survives `handlePaste`'s narrow strip).
179
- * Cursor advances naturally via `insertCharacter` on typing/paste; cursor-
180
- * movement keys (Left/Right/Home/End/word-jumps) are now functional, with
181
- * the always-end visual cursor marker drawn independently by
182
- * `WrappingSelect.renderInlineInputRow`. `viewAdapter.apply` is called
183
- * directly without a reducer round-trip — preserves the D3 fast-path
184
- * 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.
185
193
  */
186
194
  private handleIgnoreInline(data: string): void {
187
195
  if (!this.state.inputMode) return;
@@ -190,9 +198,13 @@ export class QuestionnaireSession {
190
198
  }
191
199
 
192
200
  private runtime(): QuestionnaireRuntime {
201
+ const cursor = this.inlineInput.getCursor();
202
+ const lastLine = this.inlineInput.getLines().length - 1;
193
203
  return {
194
- keybindings: getKeybindings(),
195
- inputBuffer: this.inlineInput.getValue(),
204
+ keybindings: this.keybindings,
205
+ inputBuffer: this.inlineInput.getText(),
206
+ canMoveInputUp: cursor.line > 0,
207
+ canMoveInputDown: cursor.line < lastLine,
196
208
  questions: this.questions,
197
209
  isMulti: this.isMulti,
198
210
  currentItem: this.currentItem(),
@@ -231,6 +243,6 @@ export class QuestionnaireSession {
231
243
  * happens via the `set_overlay_hidden` effect like every other side effect.
232
244
  */
233
245
  toggleCollapsedExternal(): void {
234
- this.commit({ kind: "toggle_collapsed" });
246
+ if (!this.inputEditorOpen) this.commit({ kind: "toggle_collapsed" });
235
247
  }
236
248
  }
@@ -1,22 +1,6 @@
1
1
  import type { QuestionAnswer, QuestionData } from "../../tool/types.js";
2
2
  import type { WrappingSelectItem } from "../../view/components/wrapping-select.js";
3
3
 
4
- /**
5
- * Pure derivation: does the option focused by `(currentTab, optionIndex)` carry a
6
- * non-empty `preview` string? Mode gates (notes mode, multiSelect) layer
7
- * on top via dispatch branches; this predicate is intentionally mode-agnostic.
8
- */
9
- export function computeFocusedOptionHasPreview(
10
- questions: readonly QuestionData[],
11
- currentTab: number,
12
- optionIndex: number,
13
- ): boolean {
14
- const q = questions[currentTab];
15
- if (!q) return false;
16
- const opt = q.options[optionIndex];
17
- return !!opt && typeof opt.preview === "string" && opt.preview.length > 0;
18
- }
19
-
20
4
  /**
21
5
  * Which row in the active tab should be marked as "previously confirmed"? Drives the
22
6
  * `WrappingSelect` confirmed-row indicator (label + ` ✔`) when the user navigates back
@@ -2,7 +2,6 @@ import type { QuestionAnswer, QuestionData, QuestionnaireResult } from "../tool/
2
2
  import type { WrappingSelectItem } from "../view/components/wrapping-select.js";
3
3
  import type { QuestionnaireAction } from "./key-router.js";
4
4
  import { ROW_INTENT_META } from "./row-intent.js";
5
- import { computeFocusedOptionHasPreview } from "./selectors/derivations.js";
6
5
  import type { QuestionnaireState } from "./state.js";
7
6
 
8
7
  /** Session-lifetime constants. No live-component reads — peripheral values live on canonical state. */
@@ -20,6 +19,7 @@ export interface ApplyContext {
20
19
  export type Effect =
21
20
  | { kind: "set_input_buffer"; value: string }
22
21
  | { kind: "clear_input_buffer" }
22
+ | { kind: "open_input_editor"; value: string }
23
23
  | { kind: "set_notes_value"; value: string }
24
24
  | { kind: "set_notes_focused"; focused: boolean }
25
25
  | { kind: "forward_notes_keystroke"; data: string }
@@ -47,15 +47,6 @@ function orderedAnswers(state: QuestionnaireState, questions: readonly QuestionD
47
47
  return out;
48
48
  }
49
49
 
50
- function withFocusedOptionHasPreview(
51
- state: QuestionnaireState,
52
- questions: readonly QuestionData[],
53
- ): QuestionnaireState {
54
- const focusedOptionHasPreview = computeFocusedOptionHasPreview(questions, state.currentTab, state.optionIndex);
55
- if (state.focusedOptionHasPreview === focusedOptionHasPreview) return state;
56
- return { ...state, focusedOptionHasPreview };
57
- }
58
-
59
50
  function syncMultiSelectFromAnswers(
60
51
  answers: ReadonlyMap<number, QuestionAnswer>,
61
52
  questions: readonly QuestionData[],
@@ -96,8 +87,37 @@ function persistMultiSelectAnswer(state: QuestionnaireState, ctx: ApplyContext):
96
87
  return out;
97
88
  }
98
89
 
90
+ /**
91
+ * Note text to seed the editor/draft with for a tab. The in-flight side-band store
92
+ * (`notesByTab`) is authoritative — before an option is confirmed the note lives ONLY
93
+ * there; `answer.notes` is a mirror written on exit/confirm.
94
+ */
95
+ function notesValueFor(state: QuestionnaireState, tab: number): string {
96
+ return state.notesByTab.get(tab) ?? state.answers.get(tab)?.notes ?? "";
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
+
99
119
  function switchTabResult(state: QuestionnaireState, nextTab: number, ctx: ApplyContext): ApplyResult {
100
- const notesValue = state.notesByTab.get(nextTab) ?? state.answers.get(nextTab)?.notes ?? "";
120
+ const notesValue = notesValueFor(state, nextTab);
101
121
  const transitioned: QuestionnaireState = {
102
122
  ...state,
103
123
  currentTab: nextTab,
@@ -108,12 +128,12 @@ function switchTabResult(state: QuestionnaireState, nextTab: number, ctx: ApplyC
108
128
  multiSelectChecked: syncMultiSelectFromAnswers(state.answers, ctx.questions, nextTab),
109
129
  notesDraft: notesValue,
110
130
  };
111
- const finalState = withFocusedOptionHasPreview(transitioned, ctx.questions);
112
131
  return {
113
- state: finalState,
132
+ state: transitioned,
114
133
  effects: [
115
134
  { kind: "set_notes_focused", focused: false },
116
135
  { kind: "set_notes_value", value: notesValue },
136
+ { kind: "set_input_buffer", value: customDraftValueFor(state, nextTab) },
117
137
  ],
118
138
  };
119
139
  }
@@ -137,17 +157,30 @@ const navHandler: Handler<"nav"> = (state, action, ctx) => {
137
157
  const items = ctx.itemsByTab[state.currentTab] ?? [];
138
158
  const item = items[action.nextIndex];
139
159
  const inputMode = item ? ROW_INTENT_META[item.kind].activatesInputMode : false;
140
- const next = withFocusedOptionHasPreview({ ...state, optionIndex: action.nextIndex, inputMode }, ctx.questions);
141
- if (!inputMode) {
142
- return { state: next, effects: [{ kind: "clear_input_buffer" }] };
143
- }
144
- const prior = state.answers.get(state.currentTab);
145
- if (prior?.kind === "custom" && typeof prior.answer === "string") {
146
- return { state: next, effects: [{ kind: "set_input_buffer", value: prior.answer }] };
147
- }
148
- 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
+ };
149
169
  };
150
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
+
151
184
  const tabSwitchHandler: Handler<"tab_switch"> = (state, action, ctx) => switchTabResult(state, action.nextTab, ctx);
152
185
 
153
186
  const confirmHandler: Handler<"confirm"> = (state, action, ctx) => {
@@ -169,9 +202,12 @@ const confirmHandler: Handler<"confirm"> = (state, action, ctx) => {
169
202
  // clear the checked set immediately so [✔] glyphs vanish on Enter. (A custom answer
170
203
  // carries no `selected` array, so syncMultiSelectFromAnswers keeps it empty on tab-back.)
171
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;
172
207
  const next: QuestionnaireState = {
173
208
  ...state,
174
209
  answers,
210
+ customDraftsByTab,
175
211
  ...(isCustomMulti ? { multiSelectChecked: new Set<number>() } : {}),
176
212
  };
177
213
  if (action.autoAdvanceTab !== undefined) return switchTabResult(next, action.autoAdvanceTab, ctx);
@@ -210,7 +246,7 @@ const multiConfirmHandler: Handler<"multi_confirm"> = (state, action, ctx) => {
210
246
  };
211
247
 
212
248
  const notesEnterHandler: Handler<"notes_enter"> = (state, _action, _ctx) => {
213
- const value = state.answers.get(state.currentTab)?.notes ?? "";
249
+ const value = notesValueFor(state, state.currentTab);
214
250
  return {
215
251
  state: { ...state, notesVisible: true, notesDraft: value },
216
252
  effects: [
@@ -267,6 +303,9 @@ const ignoreHandler: Handler<"ignore"> = (s, _a, _c) => ({ state: s, effects: []
267
303
  */
268
304
  const HANDLERS: { [K in QuestionnaireAction["kind"]]: Handler<K> } = {
269
305
  nav: navHandler,
306
+ input_clear: inputClearHandler,
307
+ input_edit: inputEditHandler,
308
+ input_replace: inputReplaceHandler,
270
309
  tab_switch: tabSwitchHandler,
271
310
  confirm: confirmHandler,
272
311
  toggle: toggleHandler,
package/state/state.ts CHANGED
@@ -12,14 +12,14 @@ 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
18
20
  * pass otherwise). Merged into the answer at confirm time.
19
21
  */
20
22
  notesByTab: ReadonlyMap<number, string>;
21
- /** True iff the focused option carries a non-empty `preview` string. Gates `notes_enter` and the "n to add notes" hint chip. */
22
- focusedOptionHasPreview: boolean;
23
23
  /** Focused row in the Submit-tab picker (0 = Submit, 1 = Cancel). Reset on tab switch. */
24
24
  submitChoiceIndex: number;
25
25
  /** Canonical mirror of the in-flight notes editor; runtime mirrors after `forward_notes_keystroke`. */
@@ -42,6 +42,8 @@ export interface QuestionnaireState {
42
42
  export interface QuestionnaireRuntime {
43
43
  keybindings: { matches(data: string, name: string): boolean };
44
44
  inputBuffer: string;
45
+ canMoveInputUp: boolean;
46
+ canMoveInputDown: boolean;
45
47
  questions: readonly QuestionData[];
46
48
  isMulti: boolean;
47
49
  currentItem: WrappingSelectItem | undefined;
package/tool/types.ts CHANGED
@@ -27,8 +27,8 @@ export type SentinelLabel = (typeof SENTINEL_LABELS)[SentinelKind];
27
27
  * "Other" in CC; we reject it so the runtime sentinel is the single source
28
28
  * of truth) and has no runtime kind.
29
29
  *
30
- * Reserved unconditionally — multiSelect questions also reject these labels
31
- * even though the runtime sentinel is suppressed there.
30
+ * Reserved unconditionally — every question mode rejects these labels, even
31
+ * when a given runtime sentinel is not appended in that mode.
32
32
  *
33
33
  * Order is pinned by `types.test.ts:292` — keep the explicit
34
34
  * `["Other", other, next]` literal so consumers using
@@ -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
  }