@linxiraos/pi-tui 1.4.13 → 1.5.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.
Files changed (92) hide show
  1. package/CHANGELOG.md +17 -34
  2. package/dist/types/chat/messages.d.ts +2 -0
  3. package/dist/types/chat/spotlight.d.ts +8 -3
  4. package/dist/types/chat/transcript-render-helpers.d.ts +5 -0
  5. package/dist/types/components/editor.d.ts +4 -1
  6. package/dist/types/html-form/data.d.ts +56 -0
  7. package/dist/types/html-form/dialog.d.ts +51 -0
  8. package/dist/types/html-form/media.d.ts +28 -0
  9. package/dist/types/html-form/paginate.d.ts +43 -0
  10. package/dist/types/html-form/parse.d.ts +99 -0
  11. package/dist/types/overlays/ask-dialog.d.ts +11 -6
  12. package/dist/types/overlays/copy-targets.d.ts +8 -6
  13. package/dist/types/overlays/hook-editor.d.ts +3 -1
  14. package/dist/types/overlays/hub-frame.d.ts +2 -0
  15. package/dist/types/overlays/model-hub.d.ts +2 -0
  16. package/dist/types/overlays/team-hub.d.ts +150 -0
  17. package/dist/types/render/row-moves.d.ts +41 -0
  18. package/dist/types/status-line/component.d.ts +5 -0
  19. package/dist/types/status-line/host.d.ts +2 -2
  20. package/dist/types/status-line/schema.d.ts +1 -1
  21. package/dist/types/status-line/types.d.ts +8 -0
  22. package/dist/types/tools/ask.d.ts +11 -49
  23. package/dist/types/tools/autoresearch.d.ts +2 -2
  24. package/dist/types/tools/eval.d.ts +4 -0
  25. package/dist/types/tools/grouped-file-output.d.ts +2 -0
  26. package/dist/types/tools/shell-viz.d.ts +6 -2
  27. package/dist/types/tools/xd-url.d.ts +6 -0
  28. package/dist/types/windows-input-mode.d.ts +8 -0
  29. package/package.json +9 -9
  30. package/src/charts/table-data.ts +18 -5
  31. package/src/chat/chat-transcript-builder.ts +27 -10
  32. package/src/chat/image-loading.ts +55 -0
  33. package/src/chat/messages.d.ts +2 -0
  34. package/src/chat/messages.ts +3 -0
  35. package/src/chat/spotlight.d.ts +8 -3
  36. package/src/chat/spotlight.ts +23 -11
  37. package/src/chat/tool-execution.ts +5 -0
  38. package/src/chat/transcript-render-helpers.d.ts +5 -0
  39. package/src/chat/transcript-render-helpers.ts +13 -0
  40. package/src/chrome/transcript-container.ts +1 -1
  41. package/src/components/editor.d.ts +4 -1
  42. package/src/components/editor.ts +3 -2
  43. package/src/components/markdown.ts +70 -12
  44. package/src/html-form/data.d.ts +56 -0
  45. package/src/html-form/data.ts +177 -0
  46. package/src/html-form/dialog.ts +1450 -0
  47. package/src/html-form/media.ts +105 -0
  48. package/src/html-form/paginate.ts +99 -0
  49. package/src/html-form/parse.d.ts +99 -0
  50. package/src/html-form/parse.ts +568 -0
  51. package/src/lang-from-path.ts +1 -0
  52. package/src/latex-block.ts +3 -3
  53. package/src/latex-to-unicode.ts +18 -5
  54. package/src/overlays/ask-dialog.ts +69 -52
  55. package/src/overlays/copy-targets.d.ts +8 -6
  56. package/src/overlays/copy-targets.ts +25 -46
  57. package/src/overlays/hook-editor.ts +16 -15
  58. package/src/overlays/hub-frame.ts +8 -1
  59. package/src/overlays/model-hub.ts +12 -2
  60. package/src/overlays/spotlight-sheet.ts +18 -18
  61. package/src/overlays/team-hub.ts +901 -0
  62. package/src/render/row-moves.d.ts +41 -0
  63. package/src/render/row-moves.ts +109 -0
  64. package/src/setup/wizard-overlay.ts +7 -3
  65. package/src/status-line/component.ts +19 -0
  66. package/src/status-line/footer.ts +2 -2
  67. package/src/status-line/host.ts +2 -2
  68. package/src/status-line/presets.ts +6 -6
  69. package/src/status-line/schema.ts +2 -1
  70. package/src/status-line/segments.ts +31 -4
  71. package/src/status-line/startup.ts +1 -1
  72. package/src/status-line/types.ts +8 -0
  73. package/src/stdin-buffer.ts +15 -1
  74. package/src/terminal-capabilities.ts +12 -3
  75. package/src/terminal.ts +41 -3
  76. package/src/tools/ask.d.ts +11 -49
  77. package/src/tools/ask.ts +201 -606
  78. package/src/tools/autoresearch.ts +2 -2
  79. package/src/tools/debug.ts +31 -38
  80. package/src/tools/eval.d.ts +4 -0
  81. package/src/tools/eval.ts +4 -0
  82. package/src/tools/grep.ts +38 -16
  83. package/src/tools/grouped-file-output.d.ts +2 -0
  84. package/src/tools/grouped-file-output.ts +5 -0
  85. package/src/tools/shell-viz-render.ts +37 -6
  86. package/src/tools/shell-viz.d.ts +6 -2
  87. package/src/tools/shell-viz.ts +19 -6
  88. package/src/tools/xd-url.d.ts +6 -0
  89. package/src/tools/xd-url.ts +19 -1
  90. package/src/tui.ts +129 -1
  91. package/src/windows-input-mode.d.ts +8 -0
  92. package/src/windows-input-mode.ts +13 -0
@@ -0,0 +1,1450 @@
1
+ /**
2
+ * Terminal surface for an agent-written HTML form (parsed by `parse.ts`).
3
+ *
4
+ * Row rendering lays the whole form out as one column — section titles,
5
+ * context, choice rows, one-row dropdowns, text fields, then a Submit row —
6
+ * inside a fixed-height panel. When the column is taller than the panel
7
+ * allows ({@link DIALOG_HEIGHT_RATIO} of the terminal), it splits into pages
8
+ * ({@link paginate}) at section boundaries where possible; focus drives the
9
+ * visible page, so moving past a page's last control turns the page. A native
10
+ * (Tern) terminal gets the same form described semantically instead — one
11
+ * scrolling column of sections, option lists, inputs and a Submit/Cancel bar —
12
+ * and reports clicks back through {@link HtmlFormDialog.handleNativeEvent}.
13
+ *
14
+ * Keys: ↑/↓ move between choices and fields, Tab/Shift+Tab jump fields,
15
+ * Space toggles (or opens a dropdown), ←/→ change a dropdown, Enter picks a
16
+ * radio (or leaves a field) and moves on, Enter on Submit validates and
17
+ * submits, PgUp/PgDn (←/→ on choices) turn pages, Esc cancels. With a
18
+ * `timeout`, inactivity submits the current values through `onTimeout`.
19
+ *
20
+ * @example
21
+ * const dialog = new HtmlFormDialog(parseHtmlForm(html), {
22
+ * tui,
23
+ * onSubmit: data => resolve(data), // { db: "sqlite", notes: "" }
24
+ * onCancel: () => resolve(undefined),
25
+ * });
26
+ */
27
+ import { formatKeyHint } from "../app-keybindings";
28
+ import { editorKey, editorKeys } from "../chrome/keybinding-hints";
29
+ import { OverlayPanel, PanelDivider, PanelRows } from "../chrome/overlay-box";
30
+ import { SvgFigure } from "../chat/svg-figure";
31
+ import { Editor } from "../components/editor";
32
+ import { Image } from "../components/image";
33
+ import { Input } from "../components/input";
34
+ import { renderTableRow, type TableColumn } from "../components/table";
35
+ import {
36
+ matchesSelectCancel,
37
+ matchesSelectDown,
38
+ matchesSelectPageDown,
39
+ matchesSelectPageUp,
40
+ matchesSelectUp,
41
+ } from "../keybinding-matchers";
42
+ import { getKeybindings } from "../keybindings";
43
+ import { extractPrintableText, matchesKey } from "../keys";
44
+ import { code, col, item, keyed, list, node, span, text } from "../native/describe";
45
+ import { nativeImageNode } from "../native/blobs";
46
+ import {
47
+ type DescribeContext,
48
+ leafKey,
49
+ type NativeChild,
50
+ type NativeNode,
51
+ type NativeUiEvent,
52
+ type TspSpan,
53
+ } from "../native/node";
54
+ import { actionBar, actionButton, itemIndex } from "../native/overlay";
55
+ import type { AskDialogInputGuard } from "../overlays/ask-dialog";
56
+ import { wrapPrefixedLine } from "../render/hanging-wrap";
57
+ import { getEditorTheme, type ThemeColor, theme } from "../theme/theme";
58
+ import { optionMarker } from "../tools/ask";
59
+ import type { Component, Focusable } from "../tui";
60
+ import { Ellipsis, padding, replaceTabs, truncateToWidth, visibleWidth } from "../utils";
61
+ import { choiceValue, fieldError, type HtmlFormData, type HtmlFormValue, OTHER_LABEL, textValue } from "./data";
62
+ import { type FormMedia, isSvgMedia, loadFormImage, svgMedia } from "./media";
63
+ import { BreakRank, type Page, type PageAtom, pageHeight, paginate } from "./paginate";
64
+ import {
65
+ type ChoiceField,
66
+ type ChoiceOption,
67
+ type FormBlock,
68
+ type FormField,
69
+ type FormSpan,
70
+ type HtmlForm,
71
+ spansText,
72
+ type TextField,
73
+ } from "./parse";
74
+
75
+ /** What the dialog needs from its `TUI`: the terminal's height and a way to ask for a frame. */
76
+ export interface HtmlFormHost {
77
+ readonly terminal: { readonly rows: number };
78
+ requestRender(): void;
79
+ }
80
+
81
+ /** Host wiring for {@link HtmlFormDialog}. */
82
+ export interface HtmlFormDialogOptions {
83
+ /** Panel title; `Ask` when omitted. */
84
+ title?: string;
85
+ /** Sizes the panel and repaints when the countdown ticks or a picture lands. */
86
+ tui?: HtmlFormHost;
87
+ /** Inactivity in ms after which `onTimeout` receives the current values; any input restarts it. */
88
+ timeout?: number;
89
+ onTimeout?(data: HtmlFormData): void;
90
+ /** A composer draft that keeps typing until ↑/↓ hands the keyboard to the form (as the ask dialog). */
91
+ inputGuard?: AskDialogInputGuard;
92
+ /** Directory relative `<img src>` paths resolve against; the process's when omitted. */
93
+ cwd?: string;
94
+ onSubmit(data: HtmlFormData): void;
95
+ onCancel(): void;
96
+ }
97
+
98
+ /** Fraction of the terminal the panel may occupy, as the ask dialog. */
99
+ const DIALOG_HEIGHT_RATIO = 0.7;
100
+ const MIN_BODY_ROWS = 6;
101
+ /** Top border, footer divider, footer, bottom border. */
102
+ const CHROME_ROWS = 4;
103
+ /** Column where field inputs and errors start, under the cursor and marker. */
104
+ const FIELD_INDENT = 4;
105
+ const MAX_TEXTAREA_ROWS = 10;
106
+ const DEFAULT_TITLE = "Ask";
107
+ const SUBMIT_LABEL = "Submit";
108
+ /** A text block this short right before a field is its caption and never splits from it. */
109
+ const CAPTION_MAX_ROWS = 4;
110
+ /** Tallest a picture draws, in rows, and its share of the terminal below that. */
111
+ const MAX_PICTURE_ROWS = 16;
112
+ const PICTURE_SHARE = 0.35;
113
+ /** Options a PgUp/PgDn moves an open dropdown's highlight by. */
114
+ const DROPDOWN_PAGE = 5;
115
+ /** Native action a text well's click sends, suffixed with the field index. */
116
+ const EDIT_ACT = "edit:";
117
+ /** List item key of a group's Other answer (option items are `o<index>`). */
118
+ const OTHER_ITEM = "other";
119
+ const OTHER_PLACEHOLDER = "type your own";
120
+
121
+ /** A picture block's state: still loading, failed (with why), or drawn by `rows` and described by `native`. */
122
+ type MediaSlot =
123
+ | { state: "loading" }
124
+ | { state: "failed"; reason: string }
125
+ | { state: "ready"; rows: Image | SvgFigure; native: NativeNode };
126
+
127
+ type MediaBlock = Extract<FormBlock, { kind: "image" | "svg" }>;
128
+
129
+ /** A place focus can rest: one choice option, a dropdown, a text field, or the Submit row. */
130
+ type Stop =
131
+ | { kind: "option"; field: ChoiceField; option: number }
132
+ /** The free-text Other answer of a radio/checkbox group ({@link ChoiceField.other}). */
133
+ | { kind: "other"; field: ChoiceField }
134
+ | { kind: "select"; field: ChoiceField }
135
+ | { kind: "text"; field: TextField }
136
+ | { kind: "submit" };
137
+
138
+ interface Layout {
139
+ atoms: PageAtom[];
140
+ /** Atom index of each stop, parallel to the dialog's stops. */
141
+ stopAtoms: number[];
142
+ /** Where the open dropdown hangs from: its field's atom and the value row inside it. */
143
+ dropdown?: { atom: number; row: number };
144
+ }
145
+
146
+ /** Strip control bytes a model could smuggle into labels (escape sequences, `\r`); keep `\n`. */
147
+ function sanitize(text: string): string {
148
+ return replaceTabs(text).replace(/[\x00-\x09\x0b-\x1f\x7f]/g, "");
149
+ }
150
+
151
+ /** A single select draws as a one-row dropdown; multi-selects keep option rows. */
152
+ function isDropdown(field: ChoiceField): boolean {
153
+ return field.select && !field.multi;
154
+ }
155
+
156
+ function optionText(option: ChoiceOption): string {
157
+ return sanitize(spansText(option.label)).replace(/\s+/g, " ").trim();
158
+ }
159
+
160
+ /** Split spans at hard breaks into display lines. */
161
+ function splitLines(spans: readonly FormSpan[]): FormSpan[][] {
162
+ const lines: FormSpan[][] = [[]];
163
+ for (const span of spans) {
164
+ span.text.split("\n").forEach((part, index) => {
165
+ if (index > 0) lines.push([]);
166
+ if (part) lines[lines.length - 1]!.push({ text: part, style: span.style });
167
+ });
168
+ }
169
+ return lines;
170
+ }
171
+
172
+ /** One line of spans styled over `base`; code keeps the markdown code color. */
173
+ function styleSpans(spans: readonly FormSpan[], base: (text: string) => string): string {
174
+ let out = "";
175
+ for (const span of spans) {
176
+ const text = sanitize(span.text);
177
+ if (span.style === "code") out += theme.fg("mdCode", text);
178
+ else if (span.style === "strong") out += theme.bold(base(text));
179
+ else if (span.style === "em") out += theme.italic(base(text));
180
+ else out += base(text);
181
+ }
182
+ return out;
183
+ }
184
+
185
+ /** Spans wrapped under `prefix`, continuation and hard-break rows hanging at the prefix column. */
186
+ function hang(prefix: string, spans: readonly FormSpan[], base: (text: string) => string, width: number): string[] {
187
+ const indent = padding(visibleWidth(prefix));
188
+ return splitLines(spans).flatMap((line, index) =>
189
+ wrapPrefixedLine(index === 0 ? prefix : indent, indent, styleSpans(line, base), width),
190
+ );
191
+ }
192
+
193
+ /** Form spans as native spans; `extra` tokens apply to every run. */
194
+ function nativeSpans(spans: readonly FormSpan[], extra?: string): TspSpan[] {
195
+ return spans.map(item => {
196
+ const tokens = [item.style, extra].filter(Boolean).join(" ");
197
+ return span(sanitize(item.text), tokens || undefined);
198
+ });
199
+ }
200
+
201
+ /** Interactive pager over an {@link HtmlForm}; see the module docs for layout and keys. */
202
+ export class HtmlFormDialog implements Component, Focusable {
203
+ readonly #form: HtmlForm;
204
+ readonly #options: HtmlFormDialogOptions;
205
+ readonly #stops: Stop[] = [];
206
+ readonly #fieldIndex = new Map<FormField, number>();
207
+ readonly #checked = new Map<ChoiceField, Set<number>>();
208
+ readonly #inputs = new Map<TextField, Input>();
209
+ /** The Other answer's text of each group that offers one. */
210
+ readonly #others = new Map<ChoiceField, Input>();
211
+ /** Each radio group's Other text as last seen, to notice typing from keys or the terminal. */
212
+ readonly #otherSeen = new Map<ChoiceField, string>();
213
+ readonly #editors = new Map<TextField, Editor>();
214
+ readonly #errors = new Map<FormField, string>();
215
+ readonly #panel: OverlayPanel;
216
+ readonly #body = new PanelRows();
217
+ readonly #footer = new PanelRows();
218
+ #focused = false;
219
+ #focus = 0;
220
+ #page = 0;
221
+ /**
222
+ * Whether the visible page follows focus. False while showing a page without
223
+ * stops: at open when the form leads with context, or after turning to one.
224
+ */
225
+ #followFocus = false;
226
+ #pages: Page[] = [];
227
+ #stopAtoms: number[] = [];
228
+ #height: { key: string; rows: number } | undefined;
229
+ /** The dropdown showing its options, and the option its highlight sits on. */
230
+ #open: { field: ChoiceField; highlight: number } | undefined;
231
+ #guardReleased = false;
232
+ #deadline = 0;
233
+ #tick: NodeJS.Timeout | undefined;
234
+ /** Whole seconds left on the countdown; undefined without one. */
235
+ #remaining: number | undefined;
236
+ /** Bumped on every state change; the native description is rebuilt only when it moved. */
237
+ #version = 0;
238
+ #native: { key: string; node: NativeNode } | undefined;
239
+ readonly #media = new Map<MediaBlock, MediaSlot>();
240
+ readonly #mediaAbort = new AbortController();
241
+ /** Bumped when a picture loads, fails or rasterizes: its rows change the panel's natural height. */
242
+ #mediaVersion = 0;
243
+
244
+ constructor(form: HtmlForm, options: HtmlFormDialogOptions) {
245
+ this.#form = form;
246
+ this.#options = options;
247
+ form.fields.forEach((field, index) => this.#fieldIndex.set(field, index));
248
+ for (const section of form.sections) {
249
+ for (const block of section.blocks) {
250
+ if (block.kind === "image" || block.kind === "svg") this.#initMedia(block);
251
+ if (block.kind !== "field") continue;
252
+ const field = block.field;
253
+ if (field.kind === "text") {
254
+ this.#initText(field);
255
+ this.#stops.push({ kind: "text", field });
256
+ continue;
257
+ }
258
+ this.#initChoice(field);
259
+ if (isDropdown(field)) {
260
+ if (field.options.some(option => !option.disabled)) this.#stops.push({ kind: "select", field });
261
+ continue;
262
+ }
263
+ field.options.forEach((option, index) => {
264
+ if (!option.disabled) this.#stops.push({ kind: "option", field, option: index });
265
+ });
266
+ if (field.other) {
267
+ const input = new Input();
268
+ input.prompt = "";
269
+ input.placeholder = OTHER_PLACEHOLDER;
270
+ this.#others.set(field, input);
271
+ this.#stops.push({ kind: "other", field });
272
+ }
273
+ }
274
+ }
275
+ this.#stops.push({ kind: "submit" });
276
+ this.#panel = new OverlayPanel(options.title ?? DEFAULT_TITLE);
277
+ this.#footer.setHeight(1);
278
+ this.#panel.addChild(this.#body);
279
+ this.#panel.addChild(new PanelDivider());
280
+ this.#panel.addChild(this.#footer);
281
+ this.#startCountdown();
282
+ }
283
+
284
+ get focused(): boolean {
285
+ return this.#focused;
286
+ }
287
+
288
+ set focused(value: boolean) {
289
+ this.#focused = value;
290
+ this.#syncControlFocus();
291
+ this.#changed();
292
+ }
293
+
294
+ setUseTerminalCursor(useTerminalCursor: boolean): void {
295
+ for (const input of this.#inputs.values()) input.setUseTerminalCursor(useTerminalCursor);
296
+ for (const input of this.#others.values()) input.setUseTerminalCursor(useTerminalCursor);
297
+ for (const editor of this.#editors.values()) editor.setUseTerminalCursor(useTerminalCursor);
298
+ }
299
+
300
+ /** Current answers, as submission would report them (without validating). */
301
+ data(): HtmlFormData {
302
+ const data: HtmlFormData = {};
303
+ for (const [name, value] of this.#form.hidden) data[name] = value;
304
+ for (const field of this.#form.fields) {
305
+ if (!field.name) continue;
306
+ const value = this.#value(field);
307
+ if (value !== undefined) data[field.name] = value;
308
+ }
309
+ return data;
310
+ }
311
+
312
+ debugState(): Record<string, unknown> {
313
+ const stop = this.#stops[this.#focus];
314
+ return {
315
+ page: this.#page + 1,
316
+ pages: this.#pages.length,
317
+ focus:
318
+ stop?.kind === "option"
319
+ ? `${stop.field.name}=${stop.field.options[stop.option]?.value}`
320
+ : stop?.kind === "other"
321
+ ? `${stop.field.name}=${OTHER_ITEM}`
322
+ : stop?.kind === "select" || stop?.kind === "text"
323
+ ? stop.field.name
324
+ : "submit",
325
+ open: this.#open ? this.#open.field.name : null,
326
+ media: [...this.#media.values()].map(slot =>
327
+ slot.state === "ready" ? { state: slot.state, ...slot.rows.debugState() } : slot,
328
+ ),
329
+ remaining: this.#remaining ?? null,
330
+ errors: Object.fromEntries([...this.#errors].map(([field, error]) => [field.name, error])),
331
+ data: this.data(),
332
+ };
333
+ }
334
+
335
+ handleInput(data: string): void {
336
+ this.#resetCountdown();
337
+ this.#changed();
338
+ if (this.#open) {
339
+ this.#dropdownInput(this.#open, data);
340
+ return;
341
+ }
342
+ if (matchesSelectCancel(data)) {
343
+ this.#cancel();
344
+ return;
345
+ }
346
+ if (this.#guardBlocks()) {
347
+ if (matchesSelectUp(data) || matchesSelectDown(data)) this.#guardReleased = true;
348
+ else this.#options.inputGuard?.handleInput(data);
349
+ return;
350
+ }
351
+ if (matchesSelectPageDown(data) || matchesSelectPageUp(data)) {
352
+ this.#turnPage(matchesSelectPageDown(data) ? 1 : -1);
353
+ return;
354
+ }
355
+ if (matchesKey(data, "tab") || matchesKey(data, "shift+tab")) {
356
+ this.#moveField(matchesKey(data, "shift+tab") ? -1 : 1);
357
+ return;
358
+ }
359
+ const stop = this.#stops[this.#focus]!;
360
+ // Only paged rows can hide focus; native terminals and an unrendered form never do.
361
+ if (!this.#followFocus && this.#pages.length > 1) {
362
+ // Focus sits on another page: ←/→ keep paging, and the keys that would act on
363
+ // it bring it into view instead of acting unseen. Anything else is ignored.
364
+ if (matchesKey(data, "left") || matchesKey(data, "right")) {
365
+ this.#turnPage(matchesKey(data, "right") ? 1 : -1);
366
+ } else if (
367
+ matchesSelectUp(data) ||
368
+ matchesSelectDown(data) ||
369
+ matchesKey(data, "space") ||
370
+ getKeybindings().matches(data, "tui.select.confirm")
371
+ ) {
372
+ this.#followFocus = true;
373
+ }
374
+ return;
375
+ }
376
+ if (stop.kind === "text") {
377
+ this.#textInput(stop.field, data);
378
+ return;
379
+ }
380
+ if (stop.kind === "select") {
381
+ this.#selectInput(stop.field, data);
382
+ return;
383
+ }
384
+ if (stop.kind === "other") {
385
+ this.#otherInput(stop.field, data);
386
+ return;
387
+ }
388
+ if (matchesSelectUp(data) || matchesSelectDown(data)) {
389
+ this.#moveStop(matchesSelectDown(data) ? 1 : -1);
390
+ return;
391
+ }
392
+ if (matchesKey(data, "left") || matchesKey(data, "right")) {
393
+ this.#turnPage(matchesKey(data, "right") ? 1 : -1);
394
+ return;
395
+ }
396
+ const confirm = getKeybindings().matches(data, "tui.select.confirm");
397
+ if (stop.kind === "submit") {
398
+ if (confirm) this.#submit();
399
+ return;
400
+ }
401
+ if (matchesKey(data, "space")) {
402
+ this.#toggle(stop.field, stop.option);
403
+ return;
404
+ }
405
+ if (confirm) {
406
+ if (!stop.field.multi) this.#toggle(stop.field, stop.option);
407
+ this.#moveField(1);
408
+ }
409
+ }
410
+
411
+ /** Clicks on option rows and the Submit/Cancel bar of the native description. */
412
+ handleNativeEvent(event: NativeUiEvent): void {
413
+ this.#resetCountdown();
414
+ this.#changed();
415
+ if (event.type === "action") {
416
+ if (event.act === "submit") this.#submit();
417
+ else if (event.act === "cancel") this.#cancel();
418
+ else if (event.act.startsWith(EDIT_ACT)) {
419
+ const field = this.#form.fields[Number(event.act.slice(EDIT_ACT.length))];
420
+ const stop = this.#stops.findIndex(candidate => candidate.kind === "text" && candidate.field === field);
421
+ if (stop !== -1) this.#setFocus(stop);
422
+ }
423
+ return;
424
+ }
425
+ if (event.type !== "select" && event.type !== "activate") return;
426
+ const leaf = leafKey(event.key);
427
+ const field = leaf.startsWith("f") ? this.#form.fields[Number(leaf.slice(1))] : undefined;
428
+ if (field?.kind === "choice" && field.other && event.item === OTHER_ITEM) {
429
+ // The Other row takes the keyboard (its input becomes the live editor); a radio
430
+ // group drops its pick so the typed text is the answer.
431
+ this.#setFocus(this.#stops.findIndex(stop => stop.kind === "other" && stop.field === field));
432
+ if (!field.multi) this.#checked.get(field)!.clear();
433
+ this.#errors.delete(field);
434
+ return;
435
+ }
436
+ const option = itemIndex(event.item, "o");
437
+ if (field?.kind !== "choice" || field.options[option]?.disabled !== false) return;
438
+ const stop = this.#stops.findIndex(
439
+ candidate =>
440
+ (candidate.kind === "option" && candidate.field === field && candidate.option === option) ||
441
+ (candidate.kind === "select" && candidate.field === field),
442
+ );
443
+ if (stop !== -1) this.#setFocus(stop);
444
+ if (!field.multi) this.#choose(field, option);
445
+ else if (event.type === "select") this.#toggle(field, option);
446
+ }
447
+
448
+ render(width: number): readonly string[] {
449
+ this.#options.inputGuard?.syncPresentation?.(this.#guardBlocks());
450
+ const innerWidth = Math.max(1, width - 4);
451
+ const layout = this.#layout(innerWidth);
452
+ const rows = this.#bodyRows(innerWidth, layout.atoms);
453
+ this.#pages = paginate(layout.atoms, rows);
454
+ this.#stopAtoms = layout.stopAtoms;
455
+ const focusPage = this.#pageOfAtom(layout.stopAtoms[this.#focus] ?? 0);
456
+ if (this.#followFocus) this.#page = focusPage;
457
+ this.#page = Math.min(this.#page, this.#pages.length - 1);
458
+ if (this.#page === focusPage) this.#followFocus = true;
459
+ const paging = this.#pages.length > 1 ? ` · ${this.#page + 1}/${this.#pages.length}` : "";
460
+ this.#panel.title = `${this.#titleText()}${paging}`;
461
+ this.#body.setLines(this.#renderPage(layout, this.#pages[this.#page]!, rows, innerWidth));
462
+ this.#body.setHeight(rows);
463
+ this.#footer.setLines([theme.fg("dim", this.#footerText())]);
464
+ return this.#panel.render(width);
465
+ }
466
+
467
+ /**
468
+ * The form as one native column: sections with their context, option lists
469
+ * (`select` focuses/picks, a checkbox `select` toggles), the field `Input`s and
470
+ * `Editor`s as their own described children, and a Cancel/Submit bar.
471
+ */
472
+ describe(_cx: DescribeContext): NativeNode {
473
+ const blocked = this.#guardBlocks();
474
+ this.#options.inputGuard?.syncPresentation?.(blocked);
475
+ // Other answers are typed into the terminal's own inputs, which don't pass through handleInput.
476
+ const key = `${this.#version}\0${[...this.#others.values()].map(input => input.getValue()).join("\0")}`;
477
+ if (this.#native?.key === key) return this.#native.node;
478
+ const sections = this.#form.sections.map((section, sectionIndex) => {
479
+ const blocks = section.blocks.map(block => this.#describeBlock(block));
480
+ return section.title.length > 0
481
+ ? node(
482
+ "section",
483
+ { head: nativeSpans(section.title), role: "zeta.ask.section" },
484
+ blocks,
485
+ `s${sectionIndex}`,
486
+ )
487
+ : keyed(col(blocks, { gap: "md", role: "zeta.ask.section" }), `s${sectionIndex}`);
488
+ });
489
+ const guard = this.#options.inputGuard;
490
+ const lead =
491
+ blocked && guard
492
+ ? this.#guardHint(guard)
493
+ : this.#remaining !== undefined
494
+ ? `Submits these answers in ${this.#remaining}s`
495
+ : undefined;
496
+ const described = col(
497
+ [
498
+ keyed(col(sections, { gap: "lg", role: "zeta.ask.form" }), "form"),
499
+ actionBar([
500
+ lead ? text([span(lead, "muted")], { truncate: "end", role: "zeta.ask.summary" }) : null,
501
+ ...(lead ? [null] : []),
502
+ actionButton("Cancel", "cancel", { keys: "escape" }),
503
+ actionButton(SUBMIT_LABEL, "submit", { keys: "enter", tone: "accent" }),
504
+ ]),
505
+ ],
506
+ { role: "zeta.editor.ask", gap: "md" },
507
+ );
508
+ this.#native = { key, node: described };
509
+ return described;
510
+ }
511
+
512
+ invalidate(): void {
513
+ this.#height = undefined;
514
+ this.#native = undefined;
515
+ this.#panel.invalidate();
516
+ }
517
+
518
+ dispose(): void {
519
+ this.#stopCountdown();
520
+ this.#mediaAbort.abort();
521
+ for (const slot of this.#media.values()) {
522
+ if (slot.state === "ready" && slot.rows instanceof SvgFigure) slot.rows.dispose();
523
+ }
524
+ this.#panel.dispose();
525
+ }
526
+
527
+ // ── Pictures ─────────────────────────────────────────────────────────────
528
+
529
+ /** An inline `<svg>` is ready at once; an `<img>` loads in the background and re-renders when it lands. */
530
+ #initMedia(block: MediaBlock): void {
531
+ if (block.kind === "svg") {
532
+ this.#media.set(block, this.#readyMedia(svgMedia(block.markup), block.alt || "drawing"));
533
+ return;
534
+ }
535
+ this.#media.set(block, { state: "loading" });
536
+ const signal = this.#mediaAbort.signal;
537
+ loadFormImage(block.src, { cwd: this.#options.cwd ?? process.cwd(), signal }).then(
538
+ media => this.#settleMedia(block, this.#readyMedia(media, block.alt || "image")),
539
+ (error: unknown) => {
540
+ const reason = error instanceof Error ? error.message : String(error);
541
+ this.#settleMedia(block, { state: "failed", reason });
542
+ },
543
+ );
544
+ }
545
+
546
+ #settleMedia(block: MediaBlock, slot: MediaSlot): void {
547
+ if (this.#mediaAbort.signal.aborted) return;
548
+ this.#media.set(block, slot);
549
+ this.#mediaChanged();
550
+ }
551
+
552
+ #mediaChanged(): void {
553
+ this.#mediaVersion++;
554
+ this.#changed();
555
+ this.#options.tui?.requestRender();
556
+ }
557
+
558
+ /** Rows draw a raster through {@link Image} and an SVG through {@link SvgFigure}; natively both are image blobs. */
559
+ #readyMedia(media: FormMedia, alt: string): MediaSlot {
560
+ const maxRows = this.#pictureRows();
561
+ const native = nativeImageNode(media.bytes, media.mime, { alt, max: { h: `${maxRows}lines` } });
562
+ if (isSvgMedia(media)) {
563
+ const figure = new SvgFigure({ maxRows: () => maxRows, onChange: () => this.#mediaChanged() });
564
+ figure.update(new TextDecoder().decode(media.bytes), true);
565
+ return { state: "ready", rows: figure, native };
566
+ }
567
+ const image = new Image(
568
+ media.bytes.toBase64(),
569
+ media.mime,
570
+ { fallbackColor: text => theme.fg("dim", text) },
571
+ { maxHeightCells: maxRows, filename: alt, requestRender: () => this.#mediaChanged() },
572
+ );
573
+ return { state: "ready", rows: image, native };
574
+ }
575
+
576
+ /** Rows one picture may fill: a third of the terminal, within sensible bounds. */
577
+ #pictureRows(): number {
578
+ const termRows = this.#options.tui?.terminal.rows ?? process.stdout.rows ?? 40;
579
+ return Math.max(4, Math.min(MAX_PICTURE_ROWS, Math.floor(termRows * PICTURE_SHARE)));
580
+ }
581
+
582
+ /** One dim row standing in for a picture that is loading or could not be shown. */
583
+ #mediaNote(block: MediaBlock, slot: MediaSlot): string {
584
+ const name = sanitize(block.alt || (block.kind === "image" ? block.src.slice(0, 80) : "drawing"));
585
+ if (slot.state === "failed") return `▣ ${name} — couldn't load: ${sanitize(slot.reason)}`;
586
+ return `▣ ${name} — loading…`;
587
+ }
588
+
589
+ // ── State ────────────────────────────────────────────────────────────────
590
+
591
+ #changed(): void {
592
+ this.#version++;
593
+ }
594
+
595
+ #initChoice(field: ChoiceField): void {
596
+ const checked = new Set<number>();
597
+ field.options.forEach((option, index) => {
598
+ if (!option.checked) return;
599
+ // Several checked radios: the last one wins, as in a browser.
600
+ if (!field.multi) checked.clear();
601
+ checked.add(index);
602
+ });
603
+ this.#checked.set(field, checked);
604
+ }
605
+
606
+ #initText(field: TextField): void {
607
+ if (field.multiline) {
608
+ const editor = new Editor(getEditorTheme());
609
+ editor.setBorderVisible(false);
610
+ editor.setMaxHeight(this.#textareaRows(field));
611
+ // Enter leaves the field (handled before the editor); Shift+Enter inserts newlines.
612
+ editor.disableSubmit = true;
613
+ editor.placeholder = () => field.placeholder || undefined;
614
+ // Prefilled drafts (a commit message) open at their first line, not scrolled to the end.
615
+ editor.setText(field.value, { cursor: "start" });
616
+ this.#editors.set(field, editor);
617
+ return;
618
+ }
619
+ const input = new Input();
620
+ input.prompt = "";
621
+ input.mask = field.type === "password";
622
+ input.placeholder = field.placeholder || undefined;
623
+ input.setValue(field.value);
624
+ input.onSubmit = () => this.#moveField(1);
625
+ this.#inputs.set(field, input);
626
+ }
627
+
628
+ /** Fixed textarea height: the `rows` asked for, grown to fit a prefilled draft, capped. */
629
+ #textareaRows(field: TextField): number {
630
+ const draftRows = field.value.split("\n").length;
631
+ return Math.min(MAX_TEXTAREA_ROWS, Math.max(2, field.rows, draftRows));
632
+ }
633
+
634
+ #textValue(field: TextField): string {
635
+ return field.multiline ? this.#editors.get(field)!.getExpandedText() : this.#inputs.get(field)!.getValue();
636
+ }
637
+
638
+ #value(field: FormField): HtmlFormValue | undefined {
639
+ if (field.kind === "text") return textValue(field, this.#textValue(field));
640
+ const other = this.#otherChosen(field) ? this.#others.get(field)!.getValue() : undefined;
641
+ return choiceValue(field, this.#checked.get(field)!, other);
642
+ }
643
+
644
+ /**
645
+ * Whether a group's Other answer counts: it has text and, for a radio group, no
646
+ * option is picked. Typing into a radio group's Other (from keys or the
647
+ * terminal's own edits) drops the picked option; picking an option afterwards
648
+ * keeps the text but sets Other aside.
649
+ */
650
+ #otherChosen(field: ChoiceField): boolean {
651
+ const input = this.#others.get(field);
652
+ if (!input) return false;
653
+ const text = input.getValue();
654
+ if (!field.multi && text !== (this.#otherSeen.get(field) ?? "")) {
655
+ this.#otherSeen.set(field, text);
656
+ if (text.trim() !== "") this.#checked.get(field)!.clear();
657
+ }
658
+ if (text.trim() === "") return false;
659
+ return field.multi || this.#checked.get(field)!.size === 0;
660
+ }
661
+
662
+ /** The first checked option of a single-choice field. */
663
+ #current(field: ChoiceField): number | undefined {
664
+ return this.#checked.get(field)!.values().next().value;
665
+ }
666
+
667
+ #toggle(field: ChoiceField, option: number): void {
668
+ if (!field.multi) {
669
+ this.#choose(field, option);
670
+ return;
671
+ }
672
+ const checked = this.#checked.get(field)!;
673
+ if (!checked.delete(option)) checked.add(option);
674
+ this.#errors.delete(field);
675
+ }
676
+
677
+ #choose(field: ChoiceField, option: number): void {
678
+ const checked = this.#checked.get(field)!;
679
+ checked.clear();
680
+ checked.add(option);
681
+ this.#errors.delete(field);
682
+ }
683
+
684
+ /** The nearest enabled option `delta` steps from `from`, clamped to the ends; `from` when none. */
685
+ #step(field: ChoiceField, from: number, delta: number): number {
686
+ const direction = Math.sign(delta);
687
+ let found = from;
688
+ let remaining = Math.abs(delta);
689
+ for (
690
+ let index = from + direction;
691
+ index >= 0 && index < field.options.length && remaining > 0;
692
+ index += direction
693
+ ) {
694
+ if (field.options[index]!.disabled) continue;
695
+ found = index;
696
+ remaining--;
697
+ }
698
+ return found;
699
+ }
700
+
701
+ /** The next enabled option after `from` (wrapping) whose label starts with `typed`. */
702
+ #typeAhead(field: ChoiceField, from: number, typed: string): number | undefined {
703
+ const prefix = typed.toLowerCase();
704
+ const count = field.options.length;
705
+ for (let offset = 1; offset <= count; offset++) {
706
+ const index = (from + offset) % count;
707
+ const option = field.options[index]!;
708
+ if (!option.disabled && optionText(option).toLowerCase().startsWith(prefix)) return index;
709
+ }
710
+ return undefined;
711
+ }
712
+
713
+ #submit(): void {
714
+ this.#errors.clear();
715
+ for (const field of this.#form.fields) {
716
+ const error = fieldError(field, this.#value(field));
717
+ if (error) this.#errors.set(field, error);
718
+ }
719
+ if (this.#errors.size === 0) {
720
+ this.#stopCountdown();
721
+ this.#options.onSubmit(this.data());
722
+ return;
723
+ }
724
+ const first = this.#stops.findIndex(stop => stop.kind !== "submit" && this.#errors.has(stop.field));
725
+ if (first !== -1) this.#setFocus(first);
726
+ }
727
+
728
+ #cancel(): void {
729
+ this.#stopCountdown();
730
+ this.#options.onCancel();
731
+ }
732
+
733
+ // ── Countdown ────────────────────────────────────────────────────────────
734
+
735
+ #startCountdown(): void {
736
+ const timeout = this.#options.timeout;
737
+ if (timeout === undefined || timeout <= 0) return;
738
+ this.#deadline = Date.now() + timeout;
739
+ this.#remaining = Math.ceil(timeout / 1000);
740
+ this.#tick = setInterval(() => this.#onTick(), 1000);
741
+ }
742
+
743
+ #onTick(): void {
744
+ const left = this.#deadline - Date.now();
745
+ this.#changed();
746
+ if (left <= 0) {
747
+ this.#stopCountdown();
748
+ this.#options.onTimeout?.(this.data());
749
+ return;
750
+ }
751
+ this.#remaining = Math.ceil(left / 1000);
752
+ this.#options.tui?.requestRender();
753
+ }
754
+
755
+ #resetCountdown(): void {
756
+ const timeout = this.#options.timeout;
757
+ if (this.#tick === undefined || timeout === undefined) return;
758
+ this.#deadline = Date.now() + timeout;
759
+ this.#remaining = Math.ceil(timeout / 1000);
760
+ }
761
+
762
+ #stopCountdown(): void {
763
+ clearInterval(this.#tick);
764
+ this.#tick = undefined;
765
+ this.#remaining = undefined;
766
+ }
767
+
768
+ // ── Keys ─────────────────────────────────────────────────────────────────
769
+
770
+ /** True while a draft that predates the form still owns typing. */
771
+ #guardBlocks(): boolean {
772
+ return !this.#guardReleased && (this.#options.inputGuard?.isBlocked() ?? false);
773
+ }
774
+
775
+ #guardHint(guard: AskDialogInputGuard): string {
776
+ return `${editorKeys("tui.select.up", "tui.select.down")} answer · ${guard.hint}`;
777
+ }
778
+
779
+ #textInput(field: TextField, data: string): void {
780
+ const up = matchesSelectUp(data);
781
+ const down = matchesSelectDown(data);
782
+ const editor = this.#editors.get(field);
783
+ if (!editor) {
784
+ if (up || down) {
785
+ this.#moveStop(down ? 1 : -1);
786
+ return;
787
+ }
788
+ const before = this.#textValue(field);
789
+ this.#inputs.get(field)!.handleInput(data);
790
+ if (this.#textValue(field) !== before) this.#errors.delete(field);
791
+ return;
792
+ }
793
+ const cursor = editor.getCursor();
794
+ if ((up && cursor.line === 0) || (down && cursor.line === editor.getLines().length - 1)) {
795
+ this.#moveStop(down ? 1 : -1);
796
+ return;
797
+ }
798
+ if (getKeybindings().matches(data, "tui.input.submit")) {
799
+ this.#moveField(1);
800
+ return;
801
+ }
802
+ const before = editor.getText();
803
+ editor.handleInput(data);
804
+ if (editor.getText() !== before) this.#errors.delete(field);
805
+ }
806
+
807
+ /**
808
+ * The Other row is a text field: keys type into it (typing in a radio group's
809
+ * Other drops the picked option), ↑/↓ leave it, Enter moves to the next field.
810
+ */
811
+ #otherInput(field: ChoiceField, data: string): void {
812
+ if (matchesSelectUp(data) || matchesSelectDown(data)) {
813
+ this.#moveStop(matchesSelectDown(data) ? 1 : -1);
814
+ return;
815
+ }
816
+ const input = this.#others.get(field)!;
817
+ if (getKeybindings().matches(data, "tui.select.confirm")) {
818
+ // Back on Other after picking an option: Enter makes the kept text the answer again.
819
+ if (!field.multi && input.getValue().trim() !== "") this.#checked.get(field)!.clear();
820
+ this.#moveField(1);
821
+ return;
822
+ }
823
+ const before = input.getValue();
824
+ input.handleInput(data);
825
+ if (input.getValue() !== before) this.#errors.delete(field);
826
+ }
827
+
828
+ /** A closed dropdown: ←/→ change it, Space opens it, a letter jumps to a matching option. */
829
+ #selectInput(field: ChoiceField, data: string): void {
830
+ const current = this.#current(field) ?? -1;
831
+ if (matchesSelectUp(data) || matchesSelectDown(data)) {
832
+ this.#moveStop(matchesSelectDown(data) ? 1 : -1);
833
+ return;
834
+ }
835
+ if (matchesKey(data, "left") || matchesKey(data, "right")) {
836
+ const next = this.#step(field, current, matchesKey(data, "right") ? 1 : -1);
837
+ if (next >= 0) this.#choose(field, next);
838
+ return;
839
+ }
840
+ if (matchesKey(data, "space")) {
841
+ this.#open = { field, highlight: current >= 0 ? current : this.#step(field, -1, 1) };
842
+ return;
843
+ }
844
+ if (getKeybindings().matches(data, "tui.select.confirm")) {
845
+ this.#moveField(1);
846
+ return;
847
+ }
848
+ const typed = extractPrintableText(data);
849
+ const match = typed ? this.#typeAhead(field, current, typed) : undefined;
850
+ if (match !== undefined) this.#choose(field, match);
851
+ }
852
+
853
+ /** An open dropdown owns the keys until a pick (Enter/Space), Esc or Tab closes it. */
854
+ #dropdownInput(open: { field: ChoiceField; highlight: number }, data: string): void {
855
+ if (matchesSelectCancel(data)) {
856
+ this.#open = undefined;
857
+ return;
858
+ }
859
+ if (matchesSelectUp(data) || matchesSelectDown(data)) {
860
+ open.highlight = this.#step(open.field, open.highlight, matchesSelectDown(data) ? 1 : -1);
861
+ return;
862
+ }
863
+ if (matchesSelectPageUp(data) || matchesSelectPageDown(data)) {
864
+ const delta = matchesSelectPageDown(data) ? DROPDOWN_PAGE : -DROPDOWN_PAGE;
865
+ open.highlight = this.#step(open.field, open.highlight, delta);
866
+ return;
867
+ }
868
+ if (matchesKey(data, "space") || getKeybindings().matches(data, "tui.select.confirm")) {
869
+ if (open.highlight >= 0) this.#choose(open.field, open.highlight);
870
+ this.#open = undefined;
871
+ return;
872
+ }
873
+ if (matchesKey(data, "tab") || matchesKey(data, "shift+tab")) {
874
+ this.#open = undefined;
875
+ this.#moveField(matchesKey(data, "shift+tab") ? -1 : 1);
876
+ return;
877
+ }
878
+ const typed = extractPrintableText(data);
879
+ const match = typed ? this.#typeAhead(open.field, open.highlight, typed) : undefined;
880
+ if (match !== undefined) open.highlight = match;
881
+ }
882
+
883
+ #setFocus(index: number): void {
884
+ this.#focus = Math.max(0, Math.min(this.#stops.length - 1, index));
885
+ this.#followFocus = true;
886
+ this.#syncControlFocus();
887
+ }
888
+
889
+ #moveStop(delta: number): void {
890
+ this.#setFocus(this.#focus + delta);
891
+ }
892
+
893
+ /** Jump to the first stop of the next (or previous) field; Submit counts as a field. */
894
+ #moveField(delta: number): void {
895
+ const fieldOf = (stop: Stop | undefined) => (stop && stop.kind !== "submit" ? stop.field : stop);
896
+ const current = fieldOf(this.#stops[this.#focus]);
897
+ let index = this.#focus;
898
+ while (index + delta >= 0 && index + delta < this.#stops.length && fieldOf(this.#stops[index]) === current) {
899
+ index += delta;
900
+ }
901
+ // Moving back lands on the previous field's first stop, not its last.
902
+ const target = fieldOf(this.#stops[index]);
903
+ while (delta < 0 && index > 0 && fieldOf(this.#stops[index - 1]) === target) index--;
904
+ this.#setFocus(index);
905
+ }
906
+
907
+ #turnPage(delta: number): void {
908
+ if (this.#pages.length < 2) return;
909
+ const target = Math.max(0, Math.min(this.#pages.length - 1, this.#page + delta));
910
+ const page = this.#pages[target]!;
911
+ const stop = this.#stopAtoms.findIndex(atom => atom >= page.start && atom < page.end);
912
+ if (stop !== -1) {
913
+ this.#setFocus(stop);
914
+ return;
915
+ }
916
+ this.#page = target;
917
+ this.#followFocus = false;
918
+ }
919
+
920
+ #pageOfAtom(atom: number): number {
921
+ const index = this.#pages.findIndex(page => atom >= page.start && atom < page.end);
922
+ return index === -1 ? 0 : index;
923
+ }
924
+
925
+ #syncControlFocus(): void {
926
+ const stop = this.#stops[this.#focus];
927
+ const active = stop?.kind === "text" ? stop.field : undefined;
928
+ const other = stop?.kind === "other" ? stop.field : undefined;
929
+ for (const [field, input] of this.#inputs) input.focused = this.#focused && field === active;
930
+ for (const [field, input] of this.#others) input.focused = this.#focused && field === other;
931
+ for (const [field, editor] of this.#editors) editor.focused = this.#focused && field === active;
932
+ }
933
+
934
+ // ── Rows ─────────────────────────────────────────────────────────────────
935
+
936
+ #titleText(): string {
937
+ const title = this.#options.title ?? DEFAULT_TITLE;
938
+ return this.#remaining === undefined ? title : `${title} (${this.#remaining}s)`;
939
+ }
940
+
941
+ /**
942
+ * Body rows: the whole form's natural height, capped by the terminal. Fixed
943
+ * per width, terminal height and error count, so moving focus or typing
944
+ * never resizes the panel; only a failed submit (new error rows) may.
945
+ */
946
+ #bodyRows(width: number, atoms: readonly PageAtom[]): number {
947
+ const termRows = this.#options.tui?.terminal.rows ?? process.stdout.rows ?? 40;
948
+ const key = `${width}:${termRows}:${this.#errors.size}:${this.#mediaVersion}`;
949
+ if (this.#height?.key === key) return this.#height.rows;
950
+ const cap = Math.max(MIN_BODY_ROWS, Math.floor(termRows * DIALOG_HEIGHT_RATIO) - CHROME_ROWS);
951
+ const rows = Math.min(cap, Math.max(1, pageHeight(atoms, 0, atoms.length)));
952
+ this.#height = { key, rows };
953
+ return rows;
954
+ }
955
+
956
+ #renderPage(layout: Layout, page: Page, rows: number, width: number): string[] {
957
+ const { atoms, dropdown } = layout;
958
+ const lines: string[] = [];
959
+ const continuation = atoms[page.start]?.continuation;
960
+ if (continuation !== undefined) {
961
+ lines.push(theme.fg("dim", truncateToWidth(`${continuation} (cont.)`, width, Ellipsis.Unicode)));
962
+ }
963
+ let anchor: { top: number; row: number } | undefined;
964
+ for (let index = page.start; index < page.end; index++) {
965
+ const atom = atoms[index]!;
966
+ if (index > page.start) for (let gap = 0; gap < atom.gap; gap++) lines.push("");
967
+ if (dropdown?.atom === index) anchor = { top: lines.length, row: lines.length + dropdown.row };
968
+ lines.push(...atom.lines);
969
+ }
970
+ const shown = lines.slice(0, rows);
971
+ if (anchor && this.#open && anchor.row < rows) this.#overlayDropdown(shown, anchor, rows, width);
972
+ return shown;
973
+ }
974
+
975
+ /**
976
+ * Draw the open dropdown over the page rows below its value row, or above
977
+ * its field when there is more room there. It covers rows rather than
978
+ * pushing them, so pages keep their layout while it is open.
979
+ */
980
+ #overlayDropdown(lines: string[], anchor: { top: number; row: number }, rows: number, width: number): void {
981
+ const open = this.#open!;
982
+ const below = rows - anchor.row - 1;
983
+ const above = anchor.top;
984
+ const wanted = open.field.options.length + 2;
985
+ const placeBelow = below >= Math.min(wanted, 5) || below >= above;
986
+ const box = this.#dropdownLines(open, width, placeBelow ? below : above);
987
+ if (box.length === 0) return;
988
+ const start = placeBelow ? anchor.row + 1 : anchor.top - box.length;
989
+ while (lines.length < start + box.length) lines.push("");
990
+ box.forEach((line, offset) => {
991
+ lines[start + offset] = `${padding(FIELD_INDENT - 2)}${line}`;
992
+ });
993
+ }
994
+
995
+ /** The dropdown box at most `maxRows` tall, scrolled to keep the highlight visible; empty when it cannot fit. */
996
+ #dropdownLines(open: { field: ChoiceField; highlight: number }, width: number, maxRows: number): string[] {
997
+ const options = open.field.options;
998
+ const visible = Math.min(options.length, maxRows - 2);
999
+ if (visible < 1) return [];
1000
+ const box = theme.boxRound;
1001
+ const labels = options.map(optionText);
1002
+ // Content columns: cursor (2) + label + gap (1) + current-value mark (1), padded by a column each side.
1003
+ const inner = Math.max(
1004
+ 4,
1005
+ Math.min(width - FIELD_INDENT - 4, Math.max(...labels.map(label => visibleWidth(label))) + 4),
1006
+ );
1007
+ const first = Math.max(0, Math.min(options.length - visible, open.highlight - Math.floor(visible / 2)));
1008
+ const current = this.#current(open.field);
1009
+ const edge = (left: string, right: string, more: boolean, arrow: string): string => {
1010
+ const rule = box.horizontal.repeat(inner + 2);
1011
+ const marked = more ? `${box.horizontal}${arrow}${rule.slice(2)}` : rule;
1012
+ return theme.fg("accent", `${left}${marked}${right}`);
1013
+ };
1014
+ const out = [edge(box.topLeft, box.topRight, first > 0, "↑")];
1015
+ for (let index = first; index < first + visible; index++) {
1016
+ const highlighted = index === open.highlight;
1017
+ const option = options[index]!;
1018
+ const cursor = highlighted ? `${theme.nav.cursor} ` : " ";
1019
+ const mark = index === current ? theme.fg("success", "✓") : " ";
1020
+ const color: ThemeColor = option.disabled ? "dim" : highlighted ? "accent" : "text";
1021
+ const label = truncateToWidth(labels[index]!, Math.max(1, inner - 4), Ellipsis.Unicode);
1022
+ const cell = `${theme.fg(color, `${cursor}${label}`)}${padding(inner - 3 - visibleWidth(label))}${mark}`;
1023
+ out.push(`${theme.fg("accent", `${box.vertical} `)}${cell}${theme.fg("accent", ` ${box.vertical}`)}`);
1024
+ }
1025
+ out.push(edge(box.bottomLeft, box.bottomRight, first + visible < options.length, "↓"));
1026
+ return out;
1027
+ }
1028
+
1029
+ #footerText(): string {
1030
+ const cancel = `${editorKey("tui.select.cancel")} cancel`;
1031
+ const guard = this.#options.inputGuard;
1032
+ if (guard && this.#guardBlocks()) return `${this.#guardHint(guard)} · ${cancel}`;
1033
+ const stop = this.#stops[this.#focus]!;
1034
+ const enter = formatKeyHint("enter");
1035
+ const upDown = editorKeys("tui.select.up", "tui.select.down");
1036
+ if (this.#open) return `${upDown} highlight · ${enter} choose · ${editorKey("tui.select.cancel")} close`;
1037
+ let action: string;
1038
+ if (stop.kind === "submit") action = `${enter} submit`;
1039
+ else if (stop.kind === "text") action = `${enter} next`;
1040
+ else if (stop.kind === "other") action = `type your own · ${enter} next`;
1041
+ else if (stop.kind === "select")
1042
+ action = `${formatKeyHint("space")} open · ${formatKeyHint("left")}/${formatKeyHint("right")} change · ${enter} next`;
1043
+ else if (stop.field.multi) action = `${formatKeyHint("space")} toggle · ${enter} next`;
1044
+ else action = `${enter} choose`;
1045
+ const hints = [action, `${upDown} move`, `${formatKeyHint("tab")} next field`, cancel];
1046
+ if (this.#pages.length > 1) {
1047
+ const keys =
1048
+ stop.kind === "text" || stop.kind === "select"
1049
+ ? editorKeys("tui.select.pageUp", "tui.select.pageDown")
1050
+ : `${formatKeyHint("left")}/${formatKeyHint("right")}`;
1051
+ hints.push(`${keys} page`);
1052
+ }
1053
+ return hints.join(" · ");
1054
+ }
1055
+
1056
+ #layout(width: number): Layout {
1057
+ const atoms: PageAtom[] = [];
1058
+ const stopAtoms: number[] = [];
1059
+ let dropdown: Layout["dropdown"];
1060
+ let stop = 0;
1061
+ const focusedStop = this.#focused ? this.#focus : -1;
1062
+ this.#form.sections.forEach((section, sectionIndex) => {
1063
+ const title = sanitize(spansText(section.title)).replace(/\s+/g, " ");
1064
+ let gap = sectionIndex === 0 ? 0 : 1;
1065
+ let rank = BreakRank.Section;
1066
+ if (title) {
1067
+ atoms.push({
1068
+ lines: hang("", section.title, text => theme.bold(theme.fg("text", text)), width),
1069
+ gap,
1070
+ breakRank: rank,
1071
+ });
1072
+ gap = 0;
1073
+ rank = BreakRank.Never;
1074
+ }
1075
+ /** Atom range of the text block just emitted, a candidate caption for a following field. */
1076
+ let caption: { start: number; end: number } | undefined;
1077
+ for (const block of section.blocks) {
1078
+ const blockAtoms: PageAtom[] = [];
1079
+ if (block.kind === "field") {
1080
+ // Models ask a group's question in a `<p>` right before it: keep the two as one unit.
1081
+ if (caption && caption.end - caption.start <= CAPTION_MAX_ROWS) {
1082
+ for (let index = caption.start + 1; index < caption.end; index++) {
1083
+ atoms[index]!.breakRank = BreakRank.Never;
1084
+ }
1085
+ gap = 0;
1086
+ rank = BreakRank.Never;
1087
+ }
1088
+ const field = block.field;
1089
+ for (const [atom, isStop] of this.#fieldAtoms(field, width, focusedStop, stop)) {
1090
+ if (isStop) stopAtoms[stop++] = atoms.length + blockAtoms.length;
1091
+ blockAtoms.push(atom);
1092
+ }
1093
+ if (field.kind === "choice" && this.#open?.field === field) {
1094
+ dropdown = { atom: atoms.length, row: field.label.length > 0 ? blockAtoms[0]!.lines.length - 1 : 0 };
1095
+ }
1096
+ } else {
1097
+ blockAtoms.push(...this.#contextAtoms(block, width));
1098
+ }
1099
+ if (blockAtoms.length === 0) continue;
1100
+ blockAtoms[0]!.gap = gap;
1101
+ blockAtoms[0]!.breakRank = rank;
1102
+ // No orphans or widows: a split block keeps at least two atoms on each page.
1103
+ if (blockAtoms.length > 1) {
1104
+ blockAtoms[1]!.breakRank = BreakRank.Never;
1105
+ blockAtoms[blockAtoms.length - 1]!.breakRank = BreakRank.Never;
1106
+ }
1107
+ caption =
1108
+ block.kind === "text" ? { start: atoms.length, end: atoms.length + blockAtoms.length } : undefined;
1109
+ for (const atom of blockAtoms) {
1110
+ if (title) atom.continuation = title;
1111
+ atoms.push(atom);
1112
+ }
1113
+ gap = 1;
1114
+ rank = BreakRank.Block;
1115
+ }
1116
+ });
1117
+ const submitFocused = focusedStop === this.#stops.length - 1;
1118
+ const submit = submitFocused
1119
+ ? theme.fg("accent", theme.bold(`${theme.nav.cursor} ${SUBMIT_LABEL}`))
1120
+ : theme.fg("muted", ` ${SUBMIT_LABEL}`);
1121
+ const pending = this.#errors.size > 0 ? theme.fg("error", ` ${this.#errors.size} to fix`) : "";
1122
+ stopAtoms[stop] = atoms.length;
1123
+ atoms.push({ lines: [`${submit}${pending}`], gap: 1, breakRank: BreakRank.Block });
1124
+ return { atoms, stopAtoms, dropdown };
1125
+ }
1126
+
1127
+ /** Atoms of one field, each flagged when it is a focus stop; stops are numbered from `firstStop`. */
1128
+ #fieldAtoms(field: FormField, width: number, focusedStop: number, firstStop: number): [PageAtom, boolean][] {
1129
+ const error = this.#errors.get(field);
1130
+ const errorLines = error
1131
+ ? [padding(FIELD_INDENT) + theme.fg("error", truncateToWidth(error, Math.max(1, width - FIELD_INDENT)))]
1132
+ : [];
1133
+ if (field.kind === "text" || isDropdown(field)) {
1134
+ const focused = focusedStop === firstStop;
1135
+ const lines =
1136
+ field.kind === "text"
1137
+ ? this.#textFieldLines(field, focused, width)
1138
+ : this.#dropdownFieldLines(field, focused, width);
1139
+ const hasStop = field.kind === "text" || field.options.some(option => !option.disabled);
1140
+ return [[{ lines: [...lines, ...errorLines], gap: 0, breakRank: BreakRank.Inside }, hasStop]];
1141
+ }
1142
+ const out: [PageAtom, boolean][] = [];
1143
+ if (field.label.length > 0) {
1144
+ out.push([
1145
+ {
1146
+ lines: hang(" ", field.label, text => theme.fg("text", text), width),
1147
+ gap: 0,
1148
+ breakRank: BreakRank.Inside,
1149
+ },
1150
+ false,
1151
+ ]);
1152
+ }
1153
+ const checked = this.#checked.get(field)!;
1154
+ let stop = firstStop;
1155
+ field.options.forEach((option, index) => {
1156
+ const focused = !option.disabled && focusedStop === stop;
1157
+ if (!option.disabled) stop++;
1158
+ const isChecked = checked.has(index);
1159
+ const cursor = focused ? theme.fg("accent", `${theme.nav.cursor} `) : " ";
1160
+ const marker = theme.fg(isChecked ? "success" : "dim", optionMarker(theme, field.multi, isChecked));
1161
+ const color: ThemeColor = option.disabled ? "dim" : focused ? "accent" : isChecked ? "toolOutput" : "text";
1162
+ const lines = hang(`${cursor}${marker} `, option.label, text => theme.fg(color, text), width);
1163
+ out.push([{ lines, gap: 0, breakRank: BreakRank.Inside }, !option.disabled]);
1164
+ });
1165
+ if (field.other)
1166
+ out.push([
1167
+ { lines: [this.#otherLine(field, focusedStop === stop, width)], gap: 0, breakRank: BreakRank.Inside },
1168
+ true,
1169
+ ]);
1170
+ if (errorLines.length > 0) out.push([{ lines: errorLines, gap: 0, breakRank: BreakRank.Never }, false]);
1171
+ return out;
1172
+ }
1173
+
1174
+ /** `○ Other: <text>` — an inline input while focused, else the text or a dim prompt. */
1175
+ #otherLine(field: ChoiceField, focused: boolean, width: number): string {
1176
+ const chosen = this.#otherChosen(field);
1177
+ const input = this.#others.get(field)!;
1178
+ const cursor = focused ? theme.fg("accent", `${theme.nav.cursor} `) : " ";
1179
+ const marker = theme.fg(chosen ? "success" : "dim", optionMarker(theme, field.multi, chosen));
1180
+ const label = theme.fg(focused ? "accent" : chosen ? "toolOutput" : "text", `${OTHER_LABEL}: `);
1181
+ const prefix = `${cursor}${marker} ${label}`;
1182
+ const inner = Math.max(1, width - visibleWidth(prefix));
1183
+ const value = input.getValue();
1184
+ if (focused) {
1185
+ input.cursorOverride =
1186
+ value === ""
1187
+ ? `\x1b[7m \x1b[27m${theme.fg("dim", truncateToWidth(OTHER_PLACEHOLDER, Math.max(1, inner - 1)))}`
1188
+ : undefined;
1189
+ return `${prefix}${input.render(inner)[0] ?? ""}`;
1190
+ }
1191
+ const shown = value
1192
+ ? theme.fg(chosen ? "toolOutput" : "dim", truncateToWidth(sanitize(value), inner, Ellipsis.Unicode))
1193
+ : theme.fg("dim", OTHER_PLACEHOLDER);
1194
+ return `${prefix}${shown}`;
1195
+ }
1196
+
1197
+ /** Label rows with the focus cursor, a required star and an optional dim suffix. */
1198
+ #labelLines(field: FormField, focused: boolean, suffix: string, width: number): string[] {
1199
+ const cursor = focused ? theme.fg("accent", `${theme.nav.cursor} `) : " ";
1200
+ const required = field.required ? theme.fg("error", " *") : "";
1201
+ const label = hang(cursor, field.label, text => theme.fg(focused ? "accent" : "text", text), width);
1202
+ if (label.length === 0) label.push(cursor);
1203
+ label[label.length - 1] += required + suffix;
1204
+ return label;
1205
+ }
1206
+
1207
+ /** A dropdown's label and its one value row: `‹ us-east-1 (N. Virginia) › 1/8`. */
1208
+ #dropdownFieldLines(field: ChoiceField, focused: boolean, width: number): string[] {
1209
+ const current = this.#current(field);
1210
+ const enabled = field.options.filter(option => !option.disabled).length;
1211
+ const position = current === undefined ? "" : theme.fg("dim", ` ${current + 1}/${field.options.length}`);
1212
+ const inner = Math.max(1, width - FIELD_INDENT - 4 - visibleWidth(position));
1213
+ const value =
1214
+ current === undefined
1215
+ ? theme.fg("dim", "—")
1216
+ : theme.fg(
1217
+ focused ? "accent" : "toolOutput",
1218
+ truncateToWidth(optionText(field.options[current]!), inner, Ellipsis.Unicode),
1219
+ );
1220
+ const arrows = focused && enabled > 1 ? "accent" : "dim";
1221
+ const row = `${theme.fg(arrows, "‹ ")}${value}${theme.fg(arrows, " ›")}${position}`;
1222
+ if (field.label.length === 0) {
1223
+ const cursor = focused ? theme.fg("accent", `${theme.nav.cursor} `) : " ";
1224
+ const required = field.required ? theme.fg("error", " *") : "";
1225
+ return [`${cursor}${row}${required}`];
1226
+ }
1227
+ const bar = theme.fg(focused ? "accent" : "border", theme.boxRound.vertical);
1228
+ return [...this.#labelLines(field, focused, "", width), `${padding(FIELD_INDENT - 2)}${bar} ${row}`];
1229
+ }
1230
+
1231
+ #textFieldLines(field: TextField, focused: boolean, width: number): string[] {
1232
+ const bounds =
1233
+ field.min !== undefined && field.max !== undefined
1234
+ ? `${field.min}–${field.max}`
1235
+ : field.min !== undefined
1236
+ ? `≥ ${field.min}`
1237
+ : field.max !== undefined
1238
+ ? `≤ ${field.max}`
1239
+ : "";
1240
+ const label = this.#labelLines(field, focused, bounds ? theme.fg("dim", ` ${bounds}`) : "", width);
1241
+ const bar = theme.fg(focused ? "accent" : "border", theme.boxRound.vertical);
1242
+ const prefix = `${padding(FIELD_INDENT - 2)}${bar} `;
1243
+ const inner = Math.max(1, width - FIELD_INDENT);
1244
+ const value = this.#textValue(field);
1245
+ let rows: string[];
1246
+ if (field.multiline) {
1247
+ const height = this.#textareaRows(field);
1248
+ rows = focused
1249
+ ? [...this.#editors.get(field)!.render(inner)]
1250
+ : value
1251
+ ? sanitize(value)
1252
+ .split("\n")
1253
+ .map(line => theme.fg("toolOutput", truncateToWidth(line, inner, Ellipsis.Unicode)))
1254
+ : [theme.fg("dim", truncateToWidth(sanitize(field.placeholder), inner, Ellipsis.Unicode))];
1255
+ if (rows.length > height) {
1256
+ rows = rows.slice(0, height);
1257
+ if (!focused) rows[height - 1] = theme.fg("dim", truncateToWidth("…", inner));
1258
+ }
1259
+ while (rows.length < height) rows.push("");
1260
+ } else if (focused) {
1261
+ const input = this.#inputs.get(field)!;
1262
+ input.cursorOverride =
1263
+ value === "" && field.placeholder
1264
+ ? `\x1b[7m \x1b[27m${theme.fg("dim", truncateToWidth(sanitize(field.placeholder), Math.max(1, inner - 1)))}`
1265
+ : undefined;
1266
+ rows = [...input.render(inner)];
1267
+ } else if (value) {
1268
+ const shown = field.type === "password" ? "•".repeat(value.length) : sanitize(value);
1269
+ rows = [theme.fg("toolOutput", truncateToWidth(shown, inner, Ellipsis.Unicode))];
1270
+ } else {
1271
+ rows = [theme.fg("dim", truncateToWidth(sanitize(field.placeholder), inner, Ellipsis.Unicode))];
1272
+ }
1273
+ return [...label, ...rows.map(row => `${prefix}${row}`)];
1274
+ }
1275
+
1276
+ /** Atoms of a non-field block: one per wrapped line, list item or table row. */
1277
+ #contextAtoms(block: Exclude<FormBlock, { kind: "field" }>, width: number): PageAtom[] {
1278
+ const atom = (lines: string[], breakRank = BreakRank.Inside): PageAtom => ({ lines, gap: 0, breakRank });
1279
+ switch (block.kind) {
1280
+ case "text": {
1281
+ const base = block.heading
1282
+ ? (text: string) => theme.bold(theme.fg("text", text))
1283
+ : (text: string) => theme.fg("muted", text);
1284
+ return hang("", block.spans, base, width).map(line => atom([line]));
1285
+ }
1286
+ case "list":
1287
+ return block.items.map((item, index) => {
1288
+ const bullet = theme.fg("mdListBullet", block.ordered ? `${index + 1}. ` : "• ");
1289
+ return atom(hang(bullet, item, text => theme.fg("muted", text), width));
1290
+ });
1291
+ case "pre":
1292
+ return sanitize(block.text)
1293
+ .split("\n")
1294
+ .map(line =>
1295
+ atom([
1296
+ ` ${theme.fg("mdCodeBlock", truncateToWidth(line, Math.max(1, width - 2), Ellipsis.Unicode))}`,
1297
+ ]),
1298
+ );
1299
+ case "image":
1300
+ case "svg": {
1301
+ const slot = this.#media.get(block)!;
1302
+ const rows = slot.state === "ready" ? slot.rows.render(width) : [];
1303
+ if (rows.length > 0) return [atom([...rows])];
1304
+ return [atom([theme.fg("dim", truncateToWidth(this.#mediaNote(block, slot), width, Ellipsis.Unicode))])];
1305
+ }
1306
+ case "table": {
1307
+ const cells = block.rows.map(row => row.map(cell => sanitize(spansText(cell)).replace(/\s+/g, " ")));
1308
+ const count = Math.max(0, ...cells.map(row => row.length));
1309
+ const columns: TableColumn[] = Array.from({ length: count }, (_, column) => ({
1310
+ width: Math.max(1, ...cells.map(row => visibleWidth(row[column] ?? ""))),
1311
+ minWidth: 4,
1312
+ align: "left",
1313
+ overflow: "truncate",
1314
+ }));
1315
+ const atoms = cells.map((row, index) => {
1316
+ const style =
1317
+ index < block.headerRows
1318
+ ? (text: string) => theme.bold(theme.fg("text", text))
1319
+ : (text: string) => theme.fg("muted", text);
1320
+ const padded = Array.from({ length: count }, (_, column) => ({ text: row[column] ?? "", style }));
1321
+ return atom([renderTableRow(padded, columns, width, { gap: " " })]);
1322
+ });
1323
+ if (block.headerRows > 0 && block.headerRows < atoms.length) {
1324
+ atoms.splice(block.headerRows, 0, atom([theme.fg("dim", "─".repeat(width))], BreakRank.Never));
1325
+ }
1326
+ return atoms;
1327
+ }
1328
+ }
1329
+ }
1330
+
1331
+ // ── Native ───────────────────────────────────────────────────────────────
1332
+
1333
+ #describeBlock(block: FormBlock): NativeChild {
1334
+ switch (block.kind) {
1335
+ case "text":
1336
+ return text(nativeSpans(block.spans), {
1337
+ wrap: "word",
1338
+ role: block.heading ? "zeta.ask.heading" : "zeta.ask.text",
1339
+ });
1340
+ case "list":
1341
+ return col(
1342
+ block.items.map((entry, index) =>
1343
+ text([span(block.ordered ? `${index + 1}.` : "•", "muted"), span(" "), ...nativeSpans(entry)], {
1344
+ wrap: "word",
1345
+ role: "zeta.ask.text",
1346
+ }),
1347
+ ),
1348
+ { gap: "xs", role: "zeta.ask.bullets" },
1349
+ );
1350
+ case "pre":
1351
+ return code(sanitize(block.text), { role: "zeta.ask.pre" });
1352
+ case "image":
1353
+ case "svg": {
1354
+ const slot = this.#media.get(block)!;
1355
+ if (slot.state === "ready") return slot.native;
1356
+ return text([span(this.#mediaNote(block, slot), "muted")], { role: "zeta.ask.text", truncate: "end" });
1357
+ }
1358
+ case "table": {
1359
+ const count = Math.max(0, ...block.rows.map(row => row.length));
1360
+ const header = block.headerRows > 0 ? block.rows[0] : undefined;
1361
+ const cols = Array.from({ length: count }, (_, column) => ({
1362
+ id: `c${column}`,
1363
+ head: header ? nativeSpans(header[column] ?? []) : undefined,
1364
+ }));
1365
+ const rows = block.rows.slice(block.headerRows > 0 ? 1 : 0).map((row, index) => ({
1366
+ id: `r${index}`,
1367
+ cells: Object.fromEntries(cols.map((column, cell) => [column.id, nativeSpans(row[cell] ?? [])])),
1368
+ }));
1369
+ return node("table", { cols, rows, role: "zeta.ask.table" });
1370
+ }
1371
+ case "field":
1372
+ return this.#describeField(block.field);
1373
+ }
1374
+ }
1375
+
1376
+ /**
1377
+ * The focused text field is its live `Input`/`Editor` — the only editor node
1378
+ * the form describes, so the terminal's keyboard focus (the first editor of
1379
+ * the focused component) follows the form's. Every other text field is a
1380
+ * well showing its value or placeholder; clicking it focuses the field.
1381
+ */
1382
+ #describeTextControl(field: TextField, index: number): NativeChild {
1383
+ const stop = this.#stops[this.#focus];
1384
+ if (stop?.kind === "text" && stop.field === field) {
1385
+ return field.multiline ? this.#editors.get(field)! : this.#inputs.get(field)!;
1386
+ }
1387
+ const value = this.#textValue(field);
1388
+ const shown = field.type === "password" ? "•".repeat(value.length) : sanitize(value);
1389
+ const content = shown ? [span(shown)] : [span(sanitize(field.placeholder) || " ", "dim")];
1390
+ return text(content, {
1391
+ wrap: field.multiline ? "word" : "none",
1392
+ truncate: field.multiline ? undefined : "end",
1393
+ lines: field.multiline ? this.#textareaRows(field) : 1,
1394
+ role: field.multiline ? "zeta.ask.well.multi" : "zeta.ask.well",
1395
+ actions: { click: `${EDIT_ACT}${index}` },
1396
+ });
1397
+ }
1398
+
1399
+ #describeField(field: FormField): NativeNode {
1400
+ const index = this.#fieldIndex.get(field)!;
1401
+ const error = this.#errors.get(field);
1402
+ const children: NativeChild[] = [];
1403
+ if (field.label.length > 0) {
1404
+ const required = field.required ? [span(" *", "error")] : [];
1405
+ children.push(text([...nativeSpans(field.label), ...required], { wrap: "word", role: "zeta.ask.label" }));
1406
+ }
1407
+ if (field.kind === "text") {
1408
+ children.push(this.#describeTextControl(field, index));
1409
+ } else {
1410
+ const stop = this.#stops[this.#focus];
1411
+ const focusedOption =
1412
+ stop?.kind === "option" && stop.field === field
1413
+ ? `o${stop.option}`
1414
+ : stop?.kind === "select" && stop.field === field && this.#current(field) !== undefined
1415
+ ? `o${this.#current(field)}`
1416
+ : stop?.kind === "other" && stop.field === field
1417
+ ? OTHER_ITEM
1418
+ : null;
1419
+ const checked = this.#checked.get(field)!;
1420
+ const role = field.multi ? "zeta.ask.check" : "zeta.ask.option";
1421
+ const items = field.options.map((option, optionIndex) => {
1422
+ const isChecked = checked.has(optionIndex);
1423
+ return item(`o${optionIndex}`, {
1424
+ label: nativeSpans(option.label),
1425
+ role,
1426
+ tone: isChecked ? "accent" : undefined,
1427
+ icon: field.multi && isChecked ? "check" : undefined,
1428
+ disabled: option.disabled || undefined,
1429
+ });
1430
+ });
1431
+ if (field.other) {
1432
+ const typed = sanitize(this.#others.get(field)!.getValue().trim());
1433
+ const chosen = this.#otherChosen(field);
1434
+ items.push(
1435
+ item(OTHER_ITEM, {
1436
+ label: typed ? [span(`${OTHER_LABEL}: `, "muted"), span(typed)] : [span(`${OTHER_LABEL}…`)],
1437
+ role,
1438
+ tone: chosen ? "accent" : undefined,
1439
+ icon: field.multi && chosen ? "check" : undefined,
1440
+ }),
1441
+ );
1442
+ }
1443
+ children.push(list(items, { selected: focusedOption, role: "zeta.ask.options" }, `f${index}`));
1444
+ // Typing the Other answer: its input is the form's one live editor, so the terminal focuses it.
1445
+ if (focusedOption === OTHER_ITEM) children.push(this.#others.get(field)!);
1446
+ }
1447
+ if (error) children.push(text([span(error, "error")], { role: "zeta.ask.error" }));
1448
+ return col(children, { gap: "xs", role: "zeta.ask.field" });
1449
+ }
1450
+ }