pi-cc-extensions 0.8.30 → 0.8.32

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 (53) hide show
  1. package/README.en.md +164 -174
  2. package/README.md +113 -115
  3. package/extensions/claude-code-style.ts +371 -208
  4. package/extensions/compact-thinking.ts +58 -0
  5. package/extensions/fixed-editor.ts +185 -0
  6. package/extensions/index.ts +10 -4
  7. package/extensions/subagent-notification.ts +30 -23
  8. package/node_modules/@tifan/pi-fixed-editor/README.md +36 -0
  9. package/node_modules/@tifan/pi-fixed-editor/package.json +46 -0
  10. package/node_modules/@tifan/pi-fixed-editor/src/cluster.ts +113 -0
  11. package/node_modules/@tifan/pi-fixed-editor/src/index.ts +259 -0
  12. package/node_modules/@tifan/pi-fixed-editor/src/terminal-split.ts +1337 -0
  13. package/package.json +9 -5
  14. package/extensions/ask-user-question/LICENSE +0 -21
  15. package/extensions/ask-user-question/README.md +0 -63
  16. package/extensions/ask-user-question/ask-user-question.ts +0 -266
  17. package/extensions/ask-user-question/config.ts +0 -79
  18. package/extensions/ask-user-question/events.ts +0 -55
  19. package/extensions/ask-user-question/index.ts +0 -17
  20. package/extensions/ask-user-question/reconcile.ts +0 -47
  21. package/extensions/ask-user-question/rpc-fallback.ts +0 -172
  22. package/extensions/ask-user-question/state/build-questionnaire.ts +0 -314
  23. package/extensions/ask-user-question/state/dialog-height.ts +0 -16
  24. package/extensions/ask-user-question/state/key-router.ts +0 -291
  25. package/extensions/ask-user-question/state/questionnaire-session.ts +0 -193
  26. package/extensions/ask-user-question/state/row-intent.ts +0 -143
  27. package/extensions/ask-user-question/state/selectors/contract.ts +0 -24
  28. package/extensions/ask-user-question/state/selectors/derivations.ts +0 -40
  29. package/extensions/ask-user-question/state/selectors/focus.ts +0 -17
  30. package/extensions/ask-user-question/state/selectors/projections.ts +0 -102
  31. package/extensions/ask-user-question/state/state-reducer.ts +0 -299
  32. package/extensions/ask-user-question/state/state.ts +0 -49
  33. package/extensions/ask-user-question/tool/format-answer.ts +0 -29
  34. package/extensions/ask-user-question/tool/response-envelope.ts +0 -50
  35. package/extensions/ask-user-question/tool/types.ts +0 -149
  36. package/extensions/ask-user-question/tool/validate-questionnaire.ts +0 -64
  37. package/extensions/ask-user-question/view/component-binding.ts +0 -45
  38. package/extensions/ask-user-question/view/components/inline-input.ts +0 -109
  39. package/extensions/ask-user-question/view/components/multi-select-view.ts +0 -198
  40. package/extensions/ask-user-question/view/components/option-list-view.ts +0 -77
  41. package/extensions/ask-user-question/view/components/preview/markdown-content-cache.ts +0 -76
  42. package/extensions/ask-user-question/view/components/preview/preview-block-renderer.ts +0 -114
  43. package/extensions/ask-user-question/view/components/preview/preview-box-renderer.ts +0 -86
  44. package/extensions/ask-user-question/view/components/preview/preview-layout-decider.ts +0 -219
  45. package/extensions/ask-user-question/view/components/preview/preview-pane.ts +0 -230
  46. package/extensions/ask-user-question/view/components/submit-picker.ts +0 -66
  47. package/extensions/ask-user-question/view/components/tab-bar.ts +0 -57
  48. package/extensions/ask-user-question/view/components/wrapping-select.ts +0 -307
  49. package/extensions/ask-user-question/view/dialog-builder.ts +0 -225
  50. package/extensions/ask-user-question/view/props-adapter.ts +0 -123
  51. package/extensions/ask-user-question/view/stateful-view.ts +0 -24
  52. package/extensions/ask-user-question/view/tab-components.ts +0 -16
  53. package/extensions/ask-user-question/view/tab-content-strategy.ts +0 -264
@@ -1,149 +0,0 @@
1
- import { type Static, Type } from "typebox";
2
- import { LABELS_BY_KIND, ROW_INTENT_META } from "../state/row-intent.js";
3
-
4
- export const MAX_QUESTIONS = 4;
5
- export const MIN_OPTIONS = 2;
6
- export const MAX_OPTIONS = 4;
7
- export const MAX_HEADER_LENGTH = 16;
8
- export const MAX_LABEL_LENGTH = 60;
9
-
10
- /**
11
- * User-facing labels for the three runtime sentinel rows, keyed by their
12
- * `WrappingSelectItem.kind` discriminator. Sourced from
13
- * `ROW_INTENT_META` via `LABELS_BY_KIND` (`row-intent.ts`) — single source of
14
- * truth. Adding a new sentinel requires extending the `WrappingSelectItem`
15
- * union AND adding an entry to `ROW_INTENT_META`; this map then auto-extends.
16
- */
17
- export const SENTINEL_LABELS = LABELS_BY_KIND;
18
-
19
- export type SentinelKind = keyof typeof SENTINEL_LABELS;
20
- export type SentinelLabel = (typeof SENTINEL_LABELS)[SentinelKind];
21
-
22
- /**
23
- * Labels reserved for Pi-internal sentinels — authoring an option with any
24
- * of these labels triggers the `reserved_label` runtime guard. Two of the
25
- * three come from `ROW_INTENT_META` (the runtime kinds); `"Other"` is
26
- * reserved for CC parity only (the model is conditioned to reach for
27
- * "Other" in CC; we reject it so the runtime sentinel is the single source
28
- * of truth) and has no runtime kind.
29
- *
30
- * Reserved unconditionally — every question mode rejects these labels, even
31
- * when a given runtime sentinel is not appended in that mode.
32
- *
33
- * Order is pinned by `types.test.ts:292` — keep the explicit
34
- * `["Other", other, next]` literal so consumers using
35
- * `RESERVED_LABELS[i]` indexing or `Set` membership see no behavior change.
36
- */
37
- export const RESERVED_LABELS = [
38
- "Other",
39
- ROW_INTENT_META.other.label,
40
- ROW_INTENT_META.next.label,
41
- ] as const;
42
- export type ReservedLabel = (typeof RESERVED_LABELS)[number];
43
-
44
- export const OptionSchema = Type.Object({
45
- label: Type.String({
46
- maxLength: MAX_LABEL_LENGTH,
47
- description: `MAX ${MAX_LABEL_LENGTH} CHARACTERS — hard limit, requests over the limit are rejected. The display text for this option that the user will see and select. Should be concise (1-5 words) and clearly describe the choice.`,
48
- }),
49
- description: Type.String({
50
- description:
51
- "Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications.",
52
- }),
53
- preview: Type.Optional(
54
- Type.String({
55
- description:
56
- "Optional preview content rendered when this option is focused. Use for mockups, code snippets, or visual comparisons that help users compare options. See the tool description for the expected content format.",
57
- }),
58
- ),
59
- });
60
-
61
- export const QuestionSchema = Type.Object({
62
- question: Type.String({
63
- description:
64
- 'The complete question to ask the user. Should be clear, specific, and end with a question mark. Example: "Which library should we use for date formatting?" If multiSelect is true, phrase it accordingly, e.g. "Which features do you want to enable?"',
65
- }),
66
- header: Type.String({
67
- maxLength: MAX_HEADER_LENGTH,
68
- description: `MAX ${MAX_HEADER_LENGTH} CHARACTERS — hard limit, requests over the limit are rejected. Very short chip/tag shown next to the question. Examples: "Auth method", "Library", "Approach".`,
69
- }),
70
- options: Type.Array(OptionSchema, {
71
- minItems: MIN_OPTIONS,
72
- maxItems: MAX_OPTIONS,
73
- description:
74
- "The available choices for this question. Must have 2-4 options. Each option should be a distinct, mutually exclusive choice (unless multiSelect is enabled). The 'Type something.' row is appended automatically — do NOT author it.",
75
- }),
76
- multiSelect: Type.Optional(
77
- Type.Boolean({
78
- default: false,
79
- description:
80
- "Set to true to allow the user to select multiple options instead of just one. Use when choices are not mutually exclusive.",
81
- }),
82
- ),
83
- });
84
-
85
- export const QuestionsSchema = Type.Array(QuestionSchema, {
86
- minItems: 1,
87
- maxItems: MAX_QUESTIONS,
88
- description: "Questions to ask the user (1-4 questions)",
89
- });
90
-
91
- export const QuestionParamsSchema = Type.Object({
92
- questions: QuestionsSchema,
93
- });
94
-
95
- export type OptionData = Static<typeof OptionSchema>;
96
- export type QuestionData = Static<typeof QuestionSchema>;
97
- export type QuestionParams = Static<typeof QuestionParamsSchema>;
98
-
99
- /**
100
- * Answer-intent discriminated union. `kind` is the single discriminator —
101
- * pre-1.0.3 boolean flags have been removed (see `banned-flags.test.ts`).
102
- * Mirrors the row-side `WrappingSelectItem.kind` vocabulary where possible;
103
- * `multi` is the multi-select variant (no row-side analog).
104
- *
105
- * Variant semantics:
106
- * - `option`: user picked one of the author-defined options. `answer` is the option's label.
107
- * - `custom`: user typed free-text via the "Type something." row. `answer` is the typed text or null.
108
- * - `multi`: user committed multi-select choices. `selected` carries chosen labels; `answer` is null.
109
- */
110
- export interface QuestionAnswer {
111
- questionIndex: number;
112
- question: string;
113
- kind: "option" | "custom" | "multi";
114
- answer: string | null;
115
- selected?: string[];
116
- notes?: string;
117
- /**
118
- * Markdown text from the matched option's `preview` field, populated only
119
- * when the user lands on a single-select option carrying a `preview`.
120
- * Used by `buildQuestionnaireResponse` to echo `selected preview: <preview>`
121
- * into the LLM-facing envelope. Undefined for multi-select and custom-text
122
- * (`kind: "custom"`) answers.
123
- */
124
- preview?: string;
125
- }
126
-
127
- export type QuestionnaireError =
128
- | "no_ui"
129
- | "no_custom_ui"
130
- | "no_questions"
131
- | "empty_options"
132
- | "too_many_questions"
133
- | "duplicate_question"
134
- | "duplicate_option_label"
135
- | "reserved_label"
136
- | "session_load_failed"
137
- | "stale_module_cache";
138
-
139
- export interface QuestionnaireResult {
140
- answers: QuestionAnswer[];
141
- cancelled: boolean;
142
- error?: QuestionnaireError;
143
- }
144
-
145
- export function isQuestionnaireResult(value: unknown): value is QuestionnaireResult {
146
- if (!value || typeof value !== "object") return false;
147
- const v = value as Record<string, unknown>;
148
- return Array.isArray(v.answers) && typeof v.cancelled === "boolean";
149
- }
@@ -1,64 +0,0 @@
1
- import {
2
- MAX_QUESTIONS,
3
- MIN_OPTIONS,
4
- type QuestionnaireError,
5
- type QuestionParams,
6
- RESERVED_LABELS,
7
- } from "./types.js";
8
-
9
- export const ERROR_NO_QUESTIONS = "Error: At least one question is required";
10
- export const ERROR_TOO_MANY_QUESTIONS = `Error: At most ${MAX_QUESTIONS} questions are allowed per invocation`;
11
- export const ERROR_DUPLICATE_QUESTION = "Error: Question text must be unique within an invocation";
12
- export const ERROR_TOO_FEW_OPTIONS = `Error: Each question requires at least ${MIN_OPTIONS} options`;
13
- export const ERROR_RESERVED_LABEL = `Error: Option label is reserved (${RESERVED_LABELS.join(", ")})`;
14
- export const ERROR_DUPLICATE_OPTION_LABEL = "Error: Option labels must be unique within a question";
15
-
16
- const RESERVED_LABEL_SET: ReadonlySet<string> = new Set(RESERVED_LABELS);
17
-
18
- export type ValidationResult =
19
- | { ok: true }
20
- | { ok: false; error: QuestionnaireError; message: string };
21
-
22
- /**
23
- * Pure runtime validator for `QuestionParams`. Covers every guard except
24
- * `no_ui` (which depends on `ctx.hasUI` and stays inline at the call site).
25
- * `reserved_label` MUST short-circuit before `duplicate_option_label`.
26
- */
27
- export function validateQuestionnaire(typed: QuestionParams): ValidationResult {
28
- if (typed.questions.length === 0) {
29
- return { ok: false, error: "no_questions", message: ERROR_NO_QUESTIONS };
30
- }
31
- if (typed.questions.length > MAX_QUESTIONS) {
32
- return { ok: false, error: "too_many_questions", message: ERROR_TOO_MANY_QUESTIONS };
33
- }
34
-
35
- const seenQuestions = new Set<string>();
36
- for (const q of typed.questions) {
37
- if (seenQuestions.has(q.question)) {
38
- return { ok: false, error: "duplicate_question", message: ERROR_DUPLICATE_QUESTION };
39
- }
40
- seenQuestions.add(q.question);
41
- }
42
-
43
- for (const q of typed.questions) {
44
- if (q.options.length < MIN_OPTIONS) {
45
- return { ok: false, error: "empty_options", message: ERROR_TOO_FEW_OPTIONS };
46
- }
47
- const seenLabels = new Set<string>();
48
- for (const o of q.options) {
49
- if (RESERVED_LABEL_SET.has(o.label)) {
50
- return { ok: false, error: "reserved_label", message: ERROR_RESERVED_LABEL };
51
- }
52
- if (seenLabels.has(o.label)) {
53
- return {
54
- ok: false,
55
- error: "duplicate_option_label",
56
- message: ERROR_DUPLICATE_OPTION_LABEL,
57
- };
58
- }
59
- seenLabels.add(o.label);
60
- }
61
- }
62
-
63
- return { ok: true };
64
- }
@@ -1,45 +0,0 @@
1
- import type {
2
- BindingContext,
3
- GlobalSelector,
4
- PerTabBindingContext,
5
- PerTabSelector,
6
- } from "../state/selectors/contract.js";
7
- import type { QuestionnaireState } from "../state/state.js";
8
- import type { StatefulView } from "./stateful-view.js";
9
- import type { TabComponents } from "./tab-components.js";
10
-
11
- export interface ComponentBinding<P> {
12
- readonly component: StatefulView<P>;
13
- readonly select: GlobalSelector<P>;
14
- }
15
-
16
- export interface PerTabBinding<P> {
17
- readonly resolve: (tab: TabComponents) => StatefulView<P> | undefined;
18
- readonly select: PerTabSelector<P>;
19
- readonly predicate?: PerTabSelector<boolean>;
20
- }
21
-
22
- export interface BoundGlobalBinding {
23
- apply(state: QuestionnaireState, ctx: BindingContext): void;
24
- invalidate(): void;
25
- }
26
-
27
- export interface BoundPerTabBinding {
28
- apply(state: QuestionnaireState, ctx: PerTabBindingContext): void;
29
- }
30
-
31
- export function globalBinding<P>(spec: ComponentBinding<P>): BoundGlobalBinding {
32
- return {
33
- apply: (state, ctx) => spec.component.setProps(spec.select(state, ctx)),
34
- invalidate: () => spec.component.invalidate(),
35
- };
36
- }
37
-
38
- export function perTabBinding<P>(spec: PerTabBinding<P>): BoundPerTabBinding {
39
- return {
40
- apply: (state, ctx) => {
41
- if (spec.predicate && !spec.predicate(state, ctx)) return;
42
- spec.resolve(ctx.tab)?.setProps(spec.select(state, ctx));
43
- },
44
- };
45
- }
@@ -1,109 +0,0 @@
1
- import {
2
- CURSOR_MARKER,
3
- truncateToWidth,
4
- visibleWidth,
5
- wrapTextWithAnsi,
6
- } from "@earendil-works/pi-tui";
7
-
8
- // Grapheme-aware extraction at the cursor: pi-tui's Input advances `cursor` by
9
- // grapheme-cluster code-unit length, so the cursor can land between code units of
10
- // one cluster (emoji, ZWJ, combining marks). Single-code-unit slicing would split
11
- // the cluster across the SGR 7/27 boundary. Moved here from wrapping-select.ts so
12
- // both the single-select (wrap) and multi-select (truncate-to-one-line) inline
13
- // inputs share one cursor-building core.
14
- const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
15
-
16
- export interface RenderInlineInputOptions {
17
- /** Live inline-input buffer. */
18
- buffer: string;
19
- /** Cursor offset; `undefined` / out-of-range → end-of-buffer fallback. */
20
- cursorOffset: number | undefined;
21
- /** Prefix for the first emitted line (e.g. `❯ 4. `). */
22
- rowPrefix: string;
23
- /** Prefix for continuation lines (whitespace of equal visible width). */
24
- continuationPrefix: string;
25
- /** Visible columns available for the buffer content (width − prefix width). */
26
- contentWidth: number;
27
- /** Per-line styling (single-select: `theme.selectedText`; multi-select: accent+bold). */
28
- selectedText: (text: string) => string;
29
- /**
30
- * `true` (single-select): wrap across lines at `contentWidth` (byte-identical to the
31
- * pre-extraction wrapping-select behavior).
32
- * `false` (multi-select): collapse to ONE line — truncate the plain buffer to
33
- * `contentWidth` with `…` when the cursor-marked content would overflow, keeping the
34
- * dialog height state-independent. The cursor is clipped past the visible window
35
- * (accepted trade): when the cursor-marked content fits it is rendered in full.
36
- */
37
- multiline: boolean;
38
- }
39
-
40
- /**
41
- * Resolve the cursor offset, falling back to end-of-buffer for `undefined`/out-of-range.
42
- * Mirrors the original wrapping-select.resolveOffset exactly.
43
- */
44
- function resolveCursorOffset(buffer: string, requested: number | undefined): number {
45
- if (requested !== undefined && requested >= 0 && requested <= buffer.length) return requested;
46
- return buffer.length;
47
- }
48
-
49
- /**
50
- * Build the cursor-marked raw string for the whole buffer: `before | CURSOR_MARKER |
51
- * SGR-7 reverse-video cell | SGR-27 | after`. The cell UNDER the cursor is the single
52
- * grapheme at the offset (or U+00A0 NBSP at end-of-buffer / on a literal space — NBSP is
53
- * wrap-safe where a literal space would tokenize as a wrap break). Zero characters shift;
54
- * the column under the cursor inverts. `CURSOR_MARKER` is zero-width so wrap/truncate math
55
- * is preserved.
56
- */
57
- function buildCursorRaw(buffer: string, offset: number): string {
58
- const before = buffer.slice(0, offset);
59
- const [firstGrapheme] = graphemeSegmenter.segment(buffer.slice(offset));
60
- const rawAt = firstGrapheme ? firstGrapheme.segment : "";
61
- // NBSP (U+00A0) fallback: visually identical to a space, wrap-safe.
62
- const atCursor = rawAt === "" || rawAt === " " ? "\xa0" : rawAt;
63
- const after = buffer.slice(offset + rawAt.length);
64
- return `${before}${CURSOR_MARKER}\x1b[7m${atCursor}\x1b[27m${after}`;
65
- }
66
-
67
- /**
68
- * Render the inline-input row. `multiline: true` wraps (single-select, byte-identical to
69
- * the pre-extraction output); `multiline: false` collapses to a single line.
70
- *
71
- * Cursor visualization follows the standard TUI input-widget pattern (ECMA-48 SGR 7
72
- * reverse-video on the cell AT the cursor, not an inserted glyph) — same approach used by
73
- * pi-tui Input.render, ink-text-input, terkelg/prompts, ratatui's user-input example.
74
- */
75
- export function renderInlineInputRow(opts: RenderInlineInputOptions): string[] {
76
- const {
77
- buffer,
78
- cursorOffset,
79
- rowPrefix,
80
- continuationPrefix,
81
- contentWidth,
82
- selectedText,
83
- multiline,
84
- } = opts;
85
- const offset = resolveCursorOffset(buffer, cursorOffset);
86
-
87
- if (multiline) {
88
- // Single-select: wrap at contentWidth. Byte-identical to the original
89
- // wrapping-select.renderInlineInputRow output (same raw, same wrapTextWithAnsi,
90
- // same prefix/selectedText per line).
91
- const raw = buildCursorRaw(buffer, offset);
92
- const wrapped = wrapTextWithAnsi(raw, contentWidth);
93
- return wrapped.map((segment, index) => {
94
- const prefix = index === 0 ? rowPrefix : continuationPrefix;
95
- return selectedText(`${prefix}${segment}`);
96
- });
97
- }
98
-
99
- // Multi-select: single line. Build the cursor markup on the full buffer; if it fits
100
- // contentWidth, emit it as one line. If it overflows, fall back to truncating the PLAIN
101
- // buffer (ANSI-safe — never cut a CURSOR_MARKER/SGR sequence) with `…` and clip the
102
- // cursor. This keeps the row at exactly one line so naturalHeight stays state-independent.
103
- const cursorRaw = buildCursorRaw(buffer, offset);
104
- if (visibleWidth(cursorRaw) <= contentWidth) {
105
- return [selectedText(`${rowPrefix}${cursorRaw}`)];
106
- }
107
- const clipped = truncateToWidth(buffer, contentWidth, "…");
108
- return [selectedText(`${rowPrefix}${clipped}`)];
109
- }
@@ -1,198 +0,0 @@
1
- import type { Theme } from "@earendil-works/pi-coding-agent";
2
- import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
3
- import { ROW_INTENT_META } from "../../state/row-intent.js";
4
- import type { QuestionData } from "../../tool/types.js";
5
- import type { StatefulView } from "../stateful-view.js";
6
- import { renderInlineInputRow } from "./inline-input.js";
7
-
8
- const ACTIVE_POINTER = "❯ ";
9
- const INACTIVE_POINTER = " ";
10
- const CHECKED = "[✔]";
11
- const UNCHECKED = "[ ]";
12
- const NUMBER_SEPARATOR = ". ";
13
- const BOX_LABEL_GAP = " ";
14
- // CC parity: description continuation indents to col 2 (past the pointer slot), NOT to the
15
- // full prefix column. Wrap width still uses prefixVisibleWidth so naturalHeight matches render.
16
- const CONTINUATION_INDENT = " ";
17
-
18
- export const MULTI_SUBMIT_LABEL = "Submit";
19
-
20
- export interface MultiSelectOtherRowProps {
21
- /** The "Type something." row is the focused row (optionIndex === options.length). */
22
- active: boolean;
23
- /** `state.inputMode` — true once the row has focus and keystrokes append to the buffer. */
24
- inputMode: boolean;
25
- /** Live inline-input buffer (read from `runtime.inputBuffer` / `ctx.inputBuffer`). */
26
- inputBuffer: string;
27
- inputCursorOffset: number | undefined;
28
- }
29
-
30
- export interface MultiSelectViewProps {
31
- rows: ReadonlyArray<{ checked: boolean; active: boolean }>;
32
- other: MultiSelectOtherRowProps;
33
- nextActive: boolean;
34
- nextLabel: string;
35
- }
36
-
37
- /**
38
- * Renders the multi-select option list (one row per option — pointer + checkbox + label —
39
- * plus zero or more wrapped continuation lines per description).
40
- *
41
- * `naturalHeight(width)` is state-INDEPENDENT (depends only on theme glyph widths,
42
- * question.options, and width) so the host can compute a stable globalContentHeight
43
- * without rendering. `naturalHeight(w) === render(w).length` for every props.
44
- *
45
- * `setProps(props)` is a pure field reassignment — no render, no invalidate side effects.
46
- */
47
- export class MultiSelectView implements StatefulView<MultiSelectViewProps> {
48
- private props: MultiSelectViewProps;
49
-
50
- constructor(
51
- private readonly theme: Theme,
52
- private readonly question: QuestionData,
53
- ) {
54
- this.props = {
55
- rows: [],
56
- other: { active: false, inputMode: false, inputBuffer: "", inputCursorOffset: undefined },
57
- nextActive: false,
58
- nextLabel: ROW_INTENT_META.next.label,
59
- };
60
- }
61
-
62
- setProps(props: MultiSelectViewProps): void {
63
- this.props = props;
64
- }
65
-
66
- handleInput(_data: string): void {}
67
-
68
- invalidate(): void {}
69
-
70
- render(width: number): string[] {
71
- const lines: string[] = [];
72
- const prefixWidth = this.prefixVisibleWidth();
73
- const contentWidth = Math.max(1, width - prefixWidth);
74
- const numberWidth = String(Math.max(1, this.question.options.length + 1)).length;
75
- for (let i = 0; i < this.question.options.length; i++) {
76
- const opt = this.question.options[i];
77
- const row = this.props.rows[i];
78
- if (!opt || !row) continue;
79
- const pointer = row.active ? this.theme.fg("accent", ACTIVE_POINTER) : INACTIVE_POINTER;
80
- // Checked uses the same `accent` hue as the active-row label so checked rows read
81
- // as "selected" rather than "success" — matches the visual rhythm of the rest of
82
- // the dialog (active pointer, label, picker rows are all accent).
83
- const box = row.checked
84
- ? this.theme.fg("accent", CHECKED)
85
- : this.theme.fg("muted", UNCHECKED);
86
- const label = truncateToWidth(opt.label, contentWidth, "…");
87
- const styledLabel = row.active ? this.theme.fg("accent", this.theme.bold(label)) : label;
88
- const num = String(i + 1).padStart(numberWidth, " ");
89
- const line = `${pointer}${num}${NUMBER_SEPARATOR}${box}${BOX_LABEL_GAP}${styledLabel}`;
90
- lines.push(truncateToWidth(line, width, ""));
91
- if (opt.description) {
92
- const wrapped = wrapTextWithAnsi(opt.description, contentWidth);
93
- for (const segment of wrapped) {
94
- lines.push(CONTINUATION_INDENT + this.theme.fg("muted", segment));
95
- }
96
- }
97
- }
98
-
99
- // "Type something." row — numbered N+1, box always [ ] muted UNCHECKED (never checkable).
100
- // When focused + inputMode, render the label slot via the shared inline-input helper
101
- // (single-line); otherwise the static label is truncated to contentWidth with `…`.
102
- const other = this.props.other;
103
- const otherPointer = other.active ? this.theme.fg("accent", ACTIVE_POINTER) : INACTIVE_POINTER;
104
- const otherBox = this.theme.fg("muted", UNCHECKED);
105
- const otherNum = String(this.question.options.length + 1).padStart(numberWidth, " ");
106
- let otherLabel: string;
107
- if (other.active && other.inputMode) {
108
- const rendered = renderInlineInputRow({
109
- buffer: other.inputBuffer,
110
- cursorOffset: other.inputCursorOffset,
111
- rowPrefix: "",
112
- continuationPrefix: "",
113
- contentWidth,
114
- selectedText: (t) => this.theme.fg("accent", this.theme.bold(t)),
115
- multiline: false,
116
- });
117
- otherLabel = rendered[0] ?? "";
118
- } else {
119
- const label = truncateToWidth(ROW_INTENT_META.other.label, contentWidth, "…");
120
- otherLabel = other.active ? this.theme.fg("accent", this.theme.bold(label)) : label;
121
- }
122
- lines.push(
123
- truncateToWidth(
124
- `${otherPointer}${otherNum}${NUMBER_SEPARATOR}${otherBox}${BOX_LABEL_GAP}${otherLabel}`,
125
- width,
126
- "",
127
- ),
128
- );
129
-
130
- const nextPointer = this.props.nextActive
131
- ? this.theme.fg("accent", ACTIVE_POINTER)
132
- : INACTIVE_POINTER;
133
- const nextLabel = this.props.nextActive
134
- ? this.theme.fg("accent", this.theme.bold(this.props.nextLabel))
135
- : this.props.nextLabel;
136
- lines.push(truncateToWidth(`${nextPointer}${nextLabel}`, width, ""));
137
- return lines;
138
- }
139
-
140
- /**
141
- * Returns the [startRow, endRow) range of the active (focused) row within
142
- * `render(width)`. Labels are always 1 row (truncated); descriptions wrap.
143
- */
144
- focusedItemRowRange(width: number): [number, number] {
145
- const prefixWidth = this.prefixVisibleWidth();
146
- const contentWidth = Math.max(1, width - prefixWidth);
147
- let row = 0;
148
- for (let i = 0; i < this.question.options.length; i++) {
149
- const opt = this.question.options[i];
150
- const r = this.props.rows[i];
151
- if (!opt || !r) continue;
152
- const itemHeight =
153
- 1 + (opt.description ? wrapTextWithAnsi(opt.description, contentWidth).length : 0);
154
- if (r.active) {
155
- return [row, row + itemHeight];
156
- }
157
- row += itemHeight;
158
- }
159
- // "Type something." row is always exactly 1 line (truncated, no description).
160
- if (this.props.other.active) {
161
- return [row, row + 1];
162
- }
163
- row += 1;
164
- if (this.props.nextActive) {
165
- return [row, row + 1];
166
- }
167
- return [0, 0];
168
- }
169
-
170
- naturalHeight(width: number): number {
171
- const contentWidth = Math.max(1, width - this.prefixVisibleWidth());
172
- let total = 0;
173
- for (const opt of this.question.options) {
174
- if (!opt) continue;
175
- total += 1; // row line
176
- if (opt.description) {
177
- total += wrapTextWithAnsi(opt.description, contentWidth).length;
178
- }
179
- }
180
- return total + 2; // "Type something." row + Next sentinel row (neither wraps).
181
- }
182
-
183
- private prefixVisibleWidth(): number {
184
- // Canonical prefix for OPTION rows: INACTIVE_POINTER + numberWidth digits + NUMBER_SEPARATOR
185
- // + UNCHECKED + BOX_LABEL_GAP. State-independent because ACTIVE/INACTIVE pointer share
186
- // visibleWidth, CHECKED/UNCHECKED share visibleWidth, and numberWidth is constant per question.
187
- // The number column fits `options.length + 1` so the "Type something." row's N+1 number
188
- // is never clipped. The Next sentinel uses a bare `pointer + "Next"` shape — its width
189
- // never exceeds this prefix at any reasonable terminal width, so it's safe to leave it
190
- // out of the canonical computation.
191
- const numberWidth = String(Math.max(1, this.question.options.length + 1)).length;
192
- return (
193
- visibleWidth(INACTIVE_POINTER) +
194
- numberWidth +
195
- visibleWidth(`${NUMBER_SEPARATOR}${UNCHECKED}${BOX_LABEL_GAP}`)
196
- );
197
- }
198
- }
@@ -1,77 +0,0 @@
1
- import type { StatefulView } from "../stateful-view.js";
2
- import {
3
- WrappingSelect,
4
- type WrappingSelectItem,
5
- type WrappingSelectTheme,
6
- } from "./wrapping-select.js";
7
-
8
- /**
9
- * Maximum number of option rows visible in the WrappingSelect window. Lifted here from
10
- * `preview-pane.ts` so the cap travels with the option-list owner.
11
- */
12
- export const MAX_VISIBLE_OPTIONS = 10;
13
-
14
- export interface OptionListViewConfig {
15
- items: readonly WrappingSelectItem[];
16
- theme: WrappingSelectTheme;
17
- }
18
-
19
- /**
20
- * Per-tick projection of OptionListView state. After Phase 11b, `inputBuffer`
21
- * is part of the props bag — the session-owned `inlineInput` (a headless
22
- * `pi-tui` Input instance) supplies its current `getValue()` here per tick.
23
- * `OptionListView` is purely props-driven; the imperative buffer surface and
24
- * read-back getters are gone.
25
- */
26
- export interface OptionListViewProps {
27
- selectedIndex: number;
28
- focused: boolean;
29
- inputBuffer: string;
30
- inputCursorOffset?: number;
31
- /** Optional previously-confirmed indicator. Omit when no marker should be drawn. */
32
- confirmed?: { index: number; labelOverride?: string };
33
- }
34
-
35
- /**
36
- * Sole owner of the option list's interactive state. Wraps a single
37
- * `WrappingSelect`. Implements `StatefulView<OptionListViewProps>`:
38
- * `setProps` is the only mutator; render output reflects the last props
39
- * received.
40
- */
41
- export class OptionListView implements StatefulView<OptionListViewProps> {
42
- private readonly select: WrappingSelect;
43
-
44
- constructor(config: OptionListViewConfig) {
45
- this.select = new WrappingSelect(
46
- config.items,
47
- Math.min(config.items.length, MAX_VISIBLE_OPTIONS),
48
- config.theme,
49
- {
50
- numberStartOffset: 0,
51
- totalItemsForNumbering: config.items.length,
52
- },
53
- );
54
- }
55
-
56
- setProps(props: OptionListViewProps): void {
57
- this.select.setSelectedIndex(props.selectedIndex);
58
- this.select.setFocused(props.focused);
59
- this.select.setConfirmedIndex(props.confirmed?.index, props.confirmed?.labelOverride);
60
- this.select.setInputBuffer(props.inputBuffer);
61
- this.select.setInputCursorOffset(props.inputCursorOffset);
62
- }
63
-
64
- handleInput(_data: string): void {}
65
-
66
- invalidate(): void {
67
- this.select.invalidate();
68
- }
69
-
70
- render(width: number): string[] {
71
- return this.select.render(width);
72
- }
73
-
74
- focusedItemRowRange(width: number): [number, number] {
75
- return this.select.focusedItemRowRange(width);
76
- }
77
- }