@ftrdotdev/pi-inquiry 0.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.
- package/LICENSE +21 -0
- package/README.md +161 -0
- package/package.json +68 -0
- package/src/core/domain.test.ts +154 -0
- package/src/core/domain.ts +149 -0
- package/src/core/editor.test.ts +124 -0
- package/src/core/editor.ts +78 -0
- package/src/core/flow.test.ts +445 -0
- package/src/core/flow.ts +98 -0
- package/src/core/keyboard.test.ts +44 -0
- package/src/core/keyboard.ts +59 -0
- package/src/core/machine.test.ts +438 -0
- package/src/core/machine.ts +378 -0
- package/src/core/scene.test.ts +385 -0
- package/src/core/scene.ts +555 -0
- package/src/core/services.ts +81 -0
- package/src/core/text.test.ts +77 -0
- package/src/core/text.ts +207 -0
- package/src/sdk/box-parity.test.ts +76 -0
- package/src/sdk/keys.test.ts +59 -0
- package/src/sdk/keys.ts +77 -0
- package/src/sdk/painter.ts +33 -0
- package/src/sdk/pi-ui.test.ts +185 -0
- package/src/sdk/pi-ui.ts +210 -0
- package/src/sdk/schema.test.ts +67 -0
- package/src/tool/question.test.ts +70 -0
- package/src/tool/question.ts +176 -0
|
@@ -0,0 +1,555 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scene model: the pure, terminal-agnostic rendering output of the core.
|
|
3
|
+
*
|
|
4
|
+
* A scene is a list of lines; a line is a list of spans. Each span carries
|
|
5
|
+
* plain text plus an optional style token from our own palette. The fringe
|
|
6
|
+
* painter maps style tokens to the pi theme and emits ANSI. The core never
|
|
7
|
+
* touches ANSI codes or terminal themes.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { buildBoxFrame } from "@ftrdotdev/pi-tui/box-frame";
|
|
11
|
+
import type { MachineState } from "./machine.ts";
|
|
12
|
+
import { currentOptions, isAllAnswered, type SuggestionState } from "./machine.ts";
|
|
13
|
+
import { truncateToWidth, visibleWidth } from "./text.ts";
|
|
14
|
+
import type { EditorState } from "./editor.ts";
|
|
15
|
+
|
|
16
|
+
export type Style =
|
|
17
|
+
| "accent"
|
|
18
|
+
| "border"
|
|
19
|
+
| "muted"
|
|
20
|
+
| "dim"
|
|
21
|
+
| "text"
|
|
22
|
+
| "success"
|
|
23
|
+
| "warning"
|
|
24
|
+
| "cursor"
|
|
25
|
+
| "toolTitle";
|
|
26
|
+
|
|
27
|
+
export interface Span {
|
|
28
|
+
readonly text: string;
|
|
29
|
+
readonly style?: Style;
|
|
30
|
+
readonly bold?: boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type SceneLine = readonly Span[];
|
|
34
|
+
|
|
35
|
+
export interface Scene {
|
|
36
|
+
readonly lines: readonly SceneLine[];
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export const span = (text: string, style?: Style, bold = false): Span => ({
|
|
40
|
+
text,
|
|
41
|
+
...(style === undefined ? {} : { style }),
|
|
42
|
+
...(bold ? { bold: true } : {}),
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
export const line = (...spans: readonly Span[]): SceneLine => spans;
|
|
46
|
+
|
|
47
|
+
/** Concatenated plain text of a line (used by tests and simple consumers). */
|
|
48
|
+
export const plain = (sceneLine: SceneLine): string => sceneLine.map((s) => s.text).join("");
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Word-wrap a styled line to a maximum visible width, preserving spans across
|
|
52
|
+
* line breaks. Continuation lines keep the styles of the tokens they contain.
|
|
53
|
+
* Literal newlines inside spans split lines.
|
|
54
|
+
*/
|
|
55
|
+
export const wrapLine = (content: SceneLine, width: number): readonly SceneLine[] => {
|
|
56
|
+
if (width <= 0) return [content];
|
|
57
|
+
|
|
58
|
+
// Split at literal newlines first
|
|
59
|
+
const segments: Span[][] = [[]];
|
|
60
|
+
for (const s of content) {
|
|
61
|
+
const parts = s.text.split(/(\r\n|\r|\n)/);
|
|
62
|
+
for (const part of parts) {
|
|
63
|
+
if (part === "\r\n" || part === "\r" || part === "\n") {
|
|
64
|
+
segments.push([]);
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (part !== "")
|
|
68
|
+
segments[segments.length - 1]!.push({ text: part, style: s.style, bold: s.bold });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const out: SceneLine[] = [];
|
|
73
|
+
for (const segment of segments) {
|
|
74
|
+
out.push(...wrapSegment(segment, width));
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
const wrapSegment = (segment: SceneLine, width: number): readonly SceneLine[] => {
|
|
80
|
+
if (segment.length === 0) return [[]];
|
|
81
|
+
const joined = plain(segment);
|
|
82
|
+
if (visibleWidth(joined) <= width) return [segment];
|
|
83
|
+
|
|
84
|
+
// Split spans into whitespace/non-whitespace tokens, preserving style
|
|
85
|
+
const tokens: Span[] = [];
|
|
86
|
+
for (const s of segment) {
|
|
87
|
+
for (const part of s.text.split(/(\s+)/)) {
|
|
88
|
+
if (part !== "") tokens.push({ text: part, style: s.style, bold: s.bold });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const lines: Span[][] = [];
|
|
93
|
+
let current: Span[] = [];
|
|
94
|
+
let currentWidth = 0;
|
|
95
|
+
for (const token of tokens) {
|
|
96
|
+
const tokenWidth = visibleWidth(token.text);
|
|
97
|
+
const isWhitespace = token.text.trim() === "";
|
|
98
|
+
if (tokenWidth > width && !isWhitespace) {
|
|
99
|
+
if (current.length > 0) {
|
|
100
|
+
lines.push(trimEndLine(current));
|
|
101
|
+
current = [];
|
|
102
|
+
currentWidth = 0;
|
|
103
|
+
}
|
|
104
|
+
const broken = breakLongSpan(token, width);
|
|
105
|
+
for (let i = 0; i < broken.length - 1; i++) lines.push(broken[i]!);
|
|
106
|
+
current = broken[broken.length - 1]!;
|
|
107
|
+
currentWidth = visibleWidth(plain(current));
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (currentWidth + tokenWidth > width && current.length > 0) {
|
|
111
|
+
lines.push(trimEndLine(current));
|
|
112
|
+
current = isWhitespace ? [] : [token];
|
|
113
|
+
currentWidth = isWhitespace ? 0 : tokenWidth;
|
|
114
|
+
} else {
|
|
115
|
+
if (current.length === 0 && isWhitespace) continue;
|
|
116
|
+
current.push(token);
|
|
117
|
+
currentWidth += tokenWidth;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (current.length > 0) lines.push(trimEndLine(current));
|
|
121
|
+
return lines.length > 0 ? lines : [[]];
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
const trimEndLine = (spans: Span[]): Span[] => {
|
|
125
|
+
const out = spans.slice();
|
|
126
|
+
while (out.length > 0 && out[out.length - 1]!.text.trim() === "") out.pop();
|
|
127
|
+
if (out.length === 0) return [];
|
|
128
|
+
const last = out[out.length - 1]!;
|
|
129
|
+
out[out.length - 1] = { ...last, text: last.text.trimEnd() };
|
|
130
|
+
return out;
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
const breakLongSpan = (token: Span, width: number): readonly Span[][] => {
|
|
134
|
+
const chunks: string[] = [];
|
|
135
|
+
let current = "";
|
|
136
|
+
let currentWidth = 0;
|
|
137
|
+
for (const ch of token.text) {
|
|
138
|
+
const w = visibleWidth(ch);
|
|
139
|
+
if (currentWidth + w > width && current !== "") {
|
|
140
|
+
chunks.push(current);
|
|
141
|
+
current = "";
|
|
142
|
+
currentWidth = 0;
|
|
143
|
+
}
|
|
144
|
+
current += ch;
|
|
145
|
+
currentWidth += w;
|
|
146
|
+
}
|
|
147
|
+
if (current !== "") chunks.push(current);
|
|
148
|
+
if (chunks.length === 0) chunks.push("");
|
|
149
|
+
return chunks.map((text) => [{ text, style: token.style, bold: token.bold }]);
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Build the scene for the current machine state.
|
|
154
|
+
*
|
|
155
|
+
* The whole questionnaire is framed in the house rounded border (╭─╮│╰─╯) —
|
|
156
|
+
* the same geometry `buildEditorBox` and the BorderedBox component use —
|
|
157
|
+
* replacing the legacy flat accent separators. Inside: wrapped prompt,
|
|
158
|
+
* numbered options with `→ ` selection marker (the same arrow the main
|
|
159
|
+
* editor's autocomplete popup uses), optional tab bar, inline editor box,
|
|
160
|
+
* and a help line.
|
|
161
|
+
*/
|
|
162
|
+
export const buildScene = (state: MachineState, width: number): Scene => {
|
|
163
|
+
const renderWidth = Math.max(1, width);
|
|
164
|
+
const frame = buildBoxFrame(renderWidth, { paddingX: 0 });
|
|
165
|
+
if (!frame) return { lines: [] };
|
|
166
|
+
const contentWidth = frame.contentWidth;
|
|
167
|
+
const lines: SceneLine[] = [];
|
|
168
|
+
const question = state.questions[state.currentTab];
|
|
169
|
+
const options = currentOptions(state);
|
|
170
|
+
|
|
171
|
+
const pushWrapped = (prefix: Span, content: SceneLine): void => {
|
|
172
|
+
const prefixWidth = visibleWidth(prefix.text);
|
|
173
|
+
if (prefixWidth >= contentWidth) {
|
|
174
|
+
lines.push([prefix, ...content]);
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
const wrapped = wrapLine(content, contentWidth - prefixWidth);
|
|
178
|
+
for (let i = 0; i < wrapped.length; i++) {
|
|
179
|
+
lines.push(
|
|
180
|
+
i === 0 ? [prefix, ...wrapped[i]!] : [span(" ".repeat(prefixWidth)), ...wrapped[i]!],
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
const renderOptions = (): void => {
|
|
186
|
+
for (let i = 0; i < options.length; i++) {
|
|
187
|
+
const option = options[i]!;
|
|
188
|
+
const selected = i === state.optionIndex;
|
|
189
|
+
const isOther = option.isOther;
|
|
190
|
+
const labelText = `${i + 1}. ${option.label}${isOther && state.inputMode ? " ✎" : ""}`;
|
|
191
|
+
const color = selected || (isOther && state.inputMode) ? "accent" : "text";
|
|
192
|
+
pushWrapped(selected ? span("→ ", "accent") : span(" "), [span(labelText, color)]);
|
|
193
|
+
if (option.description) {
|
|
194
|
+
pushWrapped(span(" "), [span(option.description, "muted")]);
|
|
195
|
+
} else if (option.isOther && !state.inputMode && question) {
|
|
196
|
+
// Show an existing custom answer as a subtitle under "Type something".
|
|
197
|
+
const answer = state.answers.get(question.id);
|
|
198
|
+
if (answer?.wasCustom) {
|
|
199
|
+
pushWrapped(span(" "), [span(`Current answer: ${answer.label}`, "muted")]);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
// Tab bar (multi-question mode only)
|
|
206
|
+
if (state.mode === "multi") {
|
|
207
|
+
const tabs: Span[] = [span("← ")];
|
|
208
|
+
for (let i = 0; i < state.questions.length; i++) {
|
|
209
|
+
const q = state.questions[i]!;
|
|
210
|
+
const active = i === state.currentTab;
|
|
211
|
+
const answered = state.answers.has(q.id);
|
|
212
|
+
// Active tab gets a bordered square (`▣`); finished tabs are solid
|
|
213
|
+
// (`■`), unfinished ones are outline squares (`□`). No background
|
|
214
|
+
// fill — like the editor popup, the current item is marked by symbol
|
|
215
|
+
// and accent color rather than a greyed block.
|
|
216
|
+
const box = active ? "▣" : answered ? "■" : "□";
|
|
217
|
+
const color = active ? "accent" : answered ? "success" : "muted";
|
|
218
|
+
tabs.push(span(` ${box} ${q.label} `, color), span(" "));
|
|
219
|
+
}
|
|
220
|
+
const canSubmit = isAllAnswered(state);
|
|
221
|
+
const isSubmitTab = state.currentTab === state.questions.length;
|
|
222
|
+
const submitText = " ✓ Submit ";
|
|
223
|
+
tabs.push(
|
|
224
|
+
isSubmitTab ? span(submitText, "accent") : span(submitText, canSubmit ? "success" : "dim"),
|
|
225
|
+
span(" →"),
|
|
226
|
+
);
|
|
227
|
+
pushWrapped(span(" "), tabs);
|
|
228
|
+
lines.push([]);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// Content
|
|
232
|
+
if (state.inputMode && question) {
|
|
233
|
+
pushWrapped(span(" "), [span(question.prompt, "text")]);
|
|
234
|
+
lines.push([]);
|
|
235
|
+
renderOptions();
|
|
236
|
+
lines.push([]);
|
|
237
|
+
pushWrapped(span(" "), [span("Your answer:", "muted")]);
|
|
238
|
+
// The editor box spans the content between the rails minus its 1-space
|
|
239
|
+
// gutter; the popup floats two spaces deeper under the input.
|
|
240
|
+
for (const editorLine of buildEditorBox(state.editor, Math.max(1, contentWidth - 1))) {
|
|
241
|
+
lines.push([span(" "), ...editorLine]);
|
|
242
|
+
}
|
|
243
|
+
if (state.suggestions) {
|
|
244
|
+
for (const popupLine of buildSuggestionPopup(
|
|
245
|
+
state.suggestions,
|
|
246
|
+
Math.max(1, contentWidth - 4),
|
|
247
|
+
)) {
|
|
248
|
+
lines.push([span(" "), ...popupLine]);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
lines.push([]);
|
|
252
|
+
if (state.suggestions) {
|
|
253
|
+
pushWrapped(span(" "), [span("↑↓ pick • Enter/Tab complete • Esc close", "dim")]);
|
|
254
|
+
} else {
|
|
255
|
+
pushWrapped(span(" "), [
|
|
256
|
+
span("Enter to submit • Shift+Enter for newline • Esc to go back", "dim"),
|
|
257
|
+
]);
|
|
258
|
+
}
|
|
259
|
+
} else if (state.currentTab === state.questions.length) {
|
|
260
|
+
pushWrapped(span(" "), [span("Ready to submit", "accent", true)]);
|
|
261
|
+
lines.push([]);
|
|
262
|
+
for (const q of state.questions) {
|
|
263
|
+
const answer = state.answers.get(q.id);
|
|
264
|
+
if (answer) {
|
|
265
|
+
const prefix = answer.wasCustom ? "(wrote) " : "";
|
|
266
|
+
pushWrapped(span(" "), [
|
|
267
|
+
span(`${q.label}: `, "muted"),
|
|
268
|
+
span(prefix + answer.label, "text"),
|
|
269
|
+
]);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
lines.push([]);
|
|
273
|
+
if (isAllAnswered(state)) {
|
|
274
|
+
pushWrapped(span(" "), [span("Press Enter to submit", "success")]);
|
|
275
|
+
} else {
|
|
276
|
+
const missing = state.questions
|
|
277
|
+
.filter((q) => !state.answers.has(q.id))
|
|
278
|
+
.map((q) => q.label)
|
|
279
|
+
.join(", ");
|
|
280
|
+
pushWrapped(span(" "), [span(`Unanswered: ${missing}`, "warning")]);
|
|
281
|
+
}
|
|
282
|
+
} else if (question) {
|
|
283
|
+
pushWrapped(span(" "), [span(question.prompt, "text")]);
|
|
284
|
+
lines.push([]);
|
|
285
|
+
renderOptions();
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
lines.push([]);
|
|
289
|
+
if (!state.inputMode) {
|
|
290
|
+
const help =
|
|
291
|
+
state.mode === "multi"
|
|
292
|
+
? "Tab/←→ navigate • ↑↓ select • Enter confirm • Esc cancel"
|
|
293
|
+
: "↑↓ navigate • Enter to select • Esc to cancel";
|
|
294
|
+
pushWrapped(span(" "), [span(help, "dim")]);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// Frame the interior: accent border with rails, body padded to the content
|
|
298
|
+
// width so the rails stay flush (the same layout the BorderedBox component
|
|
299
|
+
// produces around ANSI children).
|
|
300
|
+
const border = (text: string): Span => span(text, "accent");
|
|
301
|
+
const framed: SceneLine[] = [
|
|
302
|
+
[border(frame.top.left), border(frame.top.fill), border(frame.top.right)],
|
|
303
|
+
];
|
|
304
|
+
for (const content of lines) {
|
|
305
|
+
const pad = contentWidth - visibleWidth(plain(content));
|
|
306
|
+
const body = pad > 0 ? [...content, span(" ".repeat(pad))] : content;
|
|
307
|
+
framed.push([border(frame.railLeft), ...body, border(frame.railRight)]);
|
|
308
|
+
}
|
|
309
|
+
framed.push([border(frame.bottom.left), border(frame.bottom.fill), border(frame.bottom.right)]);
|
|
310
|
+
return { lines: framed };
|
|
311
|
+
};
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Build the inline editor box lines (without the leading gutter space).
|
|
315
|
+
*/
|
|
316
|
+
export const buildEditorBox = (editor: EditorState, boxWidth: number): readonly SceneLine[] => {
|
|
317
|
+
const box = Math.max(4, boxWidth);
|
|
318
|
+
const frame = buildBoxFrame(box, { paddingX: 1 });
|
|
319
|
+
if (!frame) return [];
|
|
320
|
+
const border = (text: string): Span => span(text, "border");
|
|
321
|
+
const rows = buildEditorRows(editor, frame.contentWidth);
|
|
322
|
+
return [
|
|
323
|
+
[border(frame.top.left), border(frame.top.fill), border(frame.top.right)],
|
|
324
|
+
...rows.map((row) => [
|
|
325
|
+
border(frame.railLeft),
|
|
326
|
+
span(frame.padLeft),
|
|
327
|
+
...row,
|
|
328
|
+
span(frame.padRight),
|
|
329
|
+
border(frame.railRight),
|
|
330
|
+
]),
|
|
331
|
+
[border(frame.bottom.left), border(frame.bottom.fill), border(frame.bottom.right)],
|
|
332
|
+
];
|
|
333
|
+
};
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* The editor's content rows, wrapped and padded to `contentWidth` (no frame).
|
|
337
|
+
* The cursor is a reverse-video cell that replaces the character under it, or
|
|
338
|
+
* a trailing space at the end of the text.
|
|
339
|
+
*/
|
|
340
|
+
export const buildEditorRows = (
|
|
341
|
+
editor: EditorState,
|
|
342
|
+
contentWidth: number,
|
|
343
|
+
): readonly SceneLine[] => {
|
|
344
|
+
const chars = Array.from(editor.text);
|
|
345
|
+
const cursor = Math.min(editor.cursor, chars.length);
|
|
346
|
+
|
|
347
|
+
// Split into logical lines at newlines, wrap each to the content width, and
|
|
348
|
+
// flatten into rendered rows. Each row records the UTF-16 offset of its start
|
|
349
|
+
// within the original text so the cursor can be placed precisely.
|
|
350
|
+
const rows: LayoutChunk[] = [];
|
|
351
|
+
let offset = 0;
|
|
352
|
+
for (const lineText of editor.text.split("\n")) {
|
|
353
|
+
for (const chunk of layoutChunks(lineText, contentWidth)) {
|
|
354
|
+
rows.push({ text: chunk.text, start: offset + chunk.start });
|
|
355
|
+
}
|
|
356
|
+
offset += lineText.length + 1; // +1 for the newline
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
const cursorUtf16 = chars.slice(0, cursor).join("").length;
|
|
360
|
+
let cursorRow = rows.length - 1;
|
|
361
|
+
for (let i = 0; i < rows.length; i++) {
|
|
362
|
+
const row = rows[i]!;
|
|
363
|
+
if (cursorUtf16 >= row.start && cursorUtf16 <= row.start + row.text.length) {
|
|
364
|
+
cursorRow = i;
|
|
365
|
+
break;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
const out: SceneLine[] = [];
|
|
370
|
+
for (let i = 0; i < rows.length; i++) {
|
|
371
|
+
const row = rows[i]!;
|
|
372
|
+
const rowChars = Array.from(row.text);
|
|
373
|
+
let cursorAtEnd = false;
|
|
374
|
+
let cursorCol = 0;
|
|
375
|
+
if (i === cursorRow) {
|
|
376
|
+
if (cursorUtf16 >= row.start + row.text.length) {
|
|
377
|
+
cursorAtEnd = true;
|
|
378
|
+
cursorCol = rowChars.length;
|
|
379
|
+
} else {
|
|
380
|
+
cursorCol = Array.from(row.text.slice(0, cursorUtf16 - row.start)).length;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
const spans: Span[] = [];
|
|
384
|
+
for (let j = 0; j < rowChars.length; j++) {
|
|
385
|
+
if (i === cursorRow && j === cursorCol && !cursorAtEnd) {
|
|
386
|
+
spans.push(span(rowChars[j]!, "cursor"));
|
|
387
|
+
} else {
|
|
388
|
+
spans.push(span(rowChars[j]!));
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
if (i === cursorRow && cursorAtEnd) {
|
|
392
|
+
// Reserve a trailing cell for the cursor only when the row has room:
|
|
393
|
+
// at exact fill the cursor cell would overflow the frame rails, so it
|
|
394
|
+
// is dropped (the cursor rests on the last cell — the same clipping
|
|
395
|
+
// BorderedBox applies to body rows via truncateToWidth).
|
|
396
|
+
const roomForCursor = visibleWidth(plain(spans)) + 1 <= contentWidth;
|
|
397
|
+
if (roomForCursor) spans.push(span(" ", "cursor"));
|
|
398
|
+
}
|
|
399
|
+
// Pad content to the content width so the rails stay flush (the cursor
|
|
400
|
+
// cell counts toward the width).
|
|
401
|
+
const renderedWidth = visibleWidth(plain(spans));
|
|
402
|
+
const padding = " ".repeat(Math.max(0, contentWidth - renderedWidth));
|
|
403
|
+
if (padding) spans.push(span(padding));
|
|
404
|
+
out.push(spans);
|
|
405
|
+
}
|
|
406
|
+
return out;
|
|
407
|
+
};
|
|
408
|
+
|
|
409
|
+
interface LayoutChunk {
|
|
410
|
+
readonly text: string;
|
|
411
|
+
/** UTF-16 offset of the chunk start within the original text. */
|
|
412
|
+
readonly start: number;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* Build the file-completion popup lines (without the leading gutter).
|
|
417
|
+
*
|
|
418
|
+
* Mirrors pi-tui's SelectList used by the main editor: the highlighted item
|
|
419
|
+
* is marked with `→ ` and rendered in accent foreground (the main editor's
|
|
420
|
+
* `theme.selectList.selectedText` — no background fill), descriptions align
|
|
421
|
+
* in a primary column when width allows, and a `(n/m)` indicator appears
|
|
422
|
+
* when the list overflows the visible window of five items.
|
|
423
|
+
*/
|
|
424
|
+
export const buildSuggestionPopup = (
|
|
425
|
+
suggestions: SuggestionState,
|
|
426
|
+
width: number,
|
|
427
|
+
): readonly SceneLine[] => {
|
|
428
|
+
const renderWidth = Math.max(10, width);
|
|
429
|
+
const { items, selectedIndex } = suggestions;
|
|
430
|
+
const maxVisible = 5;
|
|
431
|
+
const start = Math.max(
|
|
432
|
+
0,
|
|
433
|
+
Math.min(selectedIndex - Math.floor(maxVisible / 2), Math.max(0, items.length - maxVisible)),
|
|
434
|
+
);
|
|
435
|
+
const end = Math.min(start + maxVisible, items.length);
|
|
436
|
+
|
|
437
|
+
const lines: SceneLine[] = [];
|
|
438
|
+
for (let i = start; i < end; i++) {
|
|
439
|
+
const item = items[i]!;
|
|
440
|
+
const isSelected = i === selectedIndex;
|
|
441
|
+
const marker = isSelected ? "→ " : " ";
|
|
442
|
+
const label = item.label;
|
|
443
|
+
const description = item.description?.replace(/\r\n|\r|\n/g, " ");
|
|
444
|
+
if (description && renderWidth > 40) {
|
|
445
|
+
const primary = Math.max(1, Math.min(32, renderWidth - 6));
|
|
446
|
+
const maxPrimary = Math.max(1, primary - 2);
|
|
447
|
+
const truncatedLabel = truncateToWidth(label, maxPrimary);
|
|
448
|
+
const spacing = " ".repeat(Math.max(1, primary - visibleWidth(truncatedLabel)));
|
|
449
|
+
const remaining = renderWidth - 2 - visibleWidth(truncatedLabel) - spacing.length - 2;
|
|
450
|
+
if (remaining > 10) {
|
|
451
|
+
const truncatedDescription = truncateToWidth(description, remaining);
|
|
452
|
+
lines.push(
|
|
453
|
+
isSelected
|
|
454
|
+
? [span(marker + truncatedLabel + spacing + truncatedDescription, "accent")]
|
|
455
|
+
: [
|
|
456
|
+
span(marker),
|
|
457
|
+
span(truncatedLabel),
|
|
458
|
+
span(spacing),
|
|
459
|
+
span(truncatedDescription, "muted"),
|
|
460
|
+
],
|
|
461
|
+
);
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
const maxPrimary = renderWidth - 2;
|
|
466
|
+
const truncatedLabel = truncateToWidth(label, maxPrimary);
|
|
467
|
+
lines.push(
|
|
468
|
+
isSelected ? [span(marker + truncatedLabel, "accent")] : [span(marker), span(truncatedLabel)],
|
|
469
|
+
);
|
|
470
|
+
}
|
|
471
|
+
if (start > 0 || end < items.length) {
|
|
472
|
+
lines.push([span(` (${selectedIndex + 1}/${items.length})`, "muted")]);
|
|
473
|
+
}
|
|
474
|
+
return lines;
|
|
475
|
+
};
|
|
476
|
+
|
|
477
|
+
const layoutChunks = (text: string, width: number): readonly LayoutChunk[] => {
|
|
478
|
+
if (text === "") return [{ text: "", start: 0 }];
|
|
479
|
+
if (visibleWidth(text) <= width) return [{ text, start: 0 }];
|
|
480
|
+
|
|
481
|
+
// Whitespace-run tokens with UTF-16 offsets
|
|
482
|
+
const tokens: { text: string; start: number }[] = [];
|
|
483
|
+
const re = /\s+/g;
|
|
484
|
+
let last = 0;
|
|
485
|
+
let match: RegExpExecArray | null;
|
|
486
|
+
while ((match = re.exec(text)) !== null) {
|
|
487
|
+
if (match.index > last) tokens.push({ text: text.slice(last, match.index), start: last });
|
|
488
|
+
tokens.push({ text: match[0], start: match.index });
|
|
489
|
+
last = match.index + match[0].length;
|
|
490
|
+
}
|
|
491
|
+
if (last < text.length) tokens.push({ text: text.slice(last), start: last });
|
|
492
|
+
|
|
493
|
+
const chunks: LayoutChunk[] = [];
|
|
494
|
+
let current = "";
|
|
495
|
+
let currentStart = 0;
|
|
496
|
+
let currentWidth = 0;
|
|
497
|
+
let hasContent = false;
|
|
498
|
+
for (const token of tokens) {
|
|
499
|
+
const tokenWidth = visibleWidth(token.text);
|
|
500
|
+
const isWhitespace = token.text.trim() === "";
|
|
501
|
+
if (tokenWidth > width && !isWhitespace) {
|
|
502
|
+
if (hasContent) {
|
|
503
|
+
chunks.push({ text: current, start: currentStart });
|
|
504
|
+
current = "";
|
|
505
|
+
currentWidth = 0;
|
|
506
|
+
hasContent = false;
|
|
507
|
+
}
|
|
508
|
+
const pieces = breakLongString(token.text, width);
|
|
509
|
+
for (let i = 0; i < pieces.length - 1; i++) {
|
|
510
|
+
chunks.push({ text: pieces[i]!, start: token.start });
|
|
511
|
+
}
|
|
512
|
+
current = pieces[pieces.length - 1]!;
|
|
513
|
+
currentStart = token.start + (token.text.length - current.length);
|
|
514
|
+
currentWidth = visibleWidth(current);
|
|
515
|
+
hasContent = true;
|
|
516
|
+
continue;
|
|
517
|
+
}
|
|
518
|
+
if (currentWidth + tokenWidth > width && hasContent) {
|
|
519
|
+
chunks.push({ text: current, start: currentStart });
|
|
520
|
+
current = isWhitespace ? "" : token.text;
|
|
521
|
+
currentStart = isWhitespace ? token.start + token.text.length : token.start;
|
|
522
|
+
currentWidth = isWhitespace ? 0 : tokenWidth;
|
|
523
|
+
hasContent = !isWhitespace;
|
|
524
|
+
} else {
|
|
525
|
+
if (!hasContent && isWhitespace) continue;
|
|
526
|
+
if (!hasContent) {
|
|
527
|
+
currentStart = token.start;
|
|
528
|
+
hasContent = true;
|
|
529
|
+
}
|
|
530
|
+
current += token.text;
|
|
531
|
+
currentWidth += tokenWidth;
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
if (hasContent) chunks.push({ text: current, start: currentStart });
|
|
535
|
+
if (chunks.length === 0) chunks.push({ text: "", start: 0 });
|
|
536
|
+
return chunks;
|
|
537
|
+
};
|
|
538
|
+
|
|
539
|
+
const breakLongString = (text: string, width: number): readonly string[] => {
|
|
540
|
+
const lines: string[] = [];
|
|
541
|
+
let current = "";
|
|
542
|
+
let currentWidth = 0;
|
|
543
|
+
for (const ch of text) {
|
|
544
|
+
const w = visibleWidth(ch);
|
|
545
|
+
if (currentWidth + w > width && current !== "") {
|
|
546
|
+
lines.push(current);
|
|
547
|
+
current = "";
|
|
548
|
+
currentWidth = 0;
|
|
549
|
+
}
|
|
550
|
+
current += ch;
|
|
551
|
+
currentWidth += w;
|
|
552
|
+
}
|
|
553
|
+
if (current !== "") lines.push(current);
|
|
554
|
+
return lines.length > 0 ? lines : [""];
|
|
555
|
+
};
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Services the question flow depends on.
|
|
3
|
+
*
|
|
4
|
+
* The core defines these as abstract capabilities; the fringe (`sdk/`)
|
|
5
|
+
* implements them on top of pi's custom UI. Tests implement them with
|
|
6
|
+
* scripted fakes.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { Context, Effect } from "effect";
|
|
10
|
+
import type { KeyEvent } from "./keyboard.ts";
|
|
11
|
+
import type { QuestionResult } from "./domain.ts";
|
|
12
|
+
import type { MachineState } from "./machine.ts";
|
|
13
|
+
|
|
14
|
+
/** One entry in the file-completion popup. */
|
|
15
|
+
export interface SuggestionItem {
|
|
16
|
+
/** Full replacement text for the `@` token. */
|
|
17
|
+
readonly value: string;
|
|
18
|
+
/** Short label shown in the popup. */
|
|
19
|
+
readonly label: string;
|
|
20
|
+
readonly description?: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** A live completion session: the token prefix to replace plus the candidates. */
|
|
24
|
+
export interface CompletionState {
|
|
25
|
+
readonly prefix: string;
|
|
26
|
+
readonly items: readonly SuggestionItem[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export class Keyboard extends Context.Service<
|
|
30
|
+
Keyboard,
|
|
31
|
+
{
|
|
32
|
+
/** Wait for the next key event from the user. Blocks until one is available. */
|
|
33
|
+
nextKey(): Effect.Effect<KeyEvent>;
|
|
34
|
+
}
|
|
35
|
+
>()("inquiry/core/services/Keyboard") {}
|
|
36
|
+
|
|
37
|
+
export class Renderer extends Context.Service<
|
|
38
|
+
Renderer,
|
|
39
|
+
{
|
|
40
|
+
/** Request a redraw reflecting the given machine state. */
|
|
41
|
+
present(state: MachineState): Effect.Effect<void>;
|
|
42
|
+
/** Resolve the interaction with a final result. */
|
|
43
|
+
complete(result: QuestionResult): Effect.Effect<void>;
|
|
44
|
+
}
|
|
45
|
+
>()("inquiry/core/services/Renderer") {}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* File-reference completion for the inline editor (the `@`-token popup).
|
|
49
|
+
*
|
|
50
|
+
* The core only knows the interface; the fringe implements it on pi-tui's
|
|
51
|
+
* `CombinedAutocompleteProvider`, which is the same machinery the main editor
|
|
52
|
+
* uses, so suggestion contents and completion semantics stay identical.
|
|
53
|
+
*
|
|
54
|
+
* `cursor` is a code-point index into `text` (the core editor unit), like
|
|
55
|
+
* every other editor API in this package.
|
|
56
|
+
*/
|
|
57
|
+
export class FileSuggestions extends Context.Service<
|
|
58
|
+
FileSuggestions,
|
|
59
|
+
{
|
|
60
|
+
/**
|
|
61
|
+
* Request completions for the text before the cursor.
|
|
62
|
+
*
|
|
63
|
+
* Returns null when the text is not a completion context or no candidate
|
|
64
|
+
* matches. The popup closes when this returns null.
|
|
65
|
+
*
|
|
66
|
+
* `force` mirrors the pi editor's Tab behavior: query even outside an `@`
|
|
67
|
+
* context so plain path tokens and directory continuations complete.
|
|
68
|
+
*/
|
|
69
|
+
query(text: string, cursor: number, force?: boolean): Effect.Effect<CompletionState | null>;
|
|
70
|
+
/**
|
|
71
|
+
* Replace the `@` token with the chosen item, returning the new editor
|
|
72
|
+
* text and cursor (code-point index).
|
|
73
|
+
*/
|
|
74
|
+
apply(
|
|
75
|
+
text: string,
|
|
76
|
+
cursor: number,
|
|
77
|
+
item: SuggestionItem,
|
|
78
|
+
prefix: string,
|
|
79
|
+
): Effect.Effect<{ readonly text: string; readonly cursor: number }>;
|
|
80
|
+
}
|
|
81
|
+
>()("inquiry/core/services/FileSuggestions") {}
|