@ftrdotdev/pi-tui 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.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +63 -0
  3. package/package.json +80 -0
  4. package/src/autocomplete-contract.test.ts +126 -0
  5. package/src/autocomplete-contract.ts +91 -0
  6. package/src/commands/git-execution.test.ts +69 -0
  7. package/src/commands/git-execution.ts +198 -0
  8. package/src/commands/git-status.test.ts +379 -0
  9. package/src/commands/git-status.ts +320 -0
  10. package/src/components/bordered-box.test.ts +136 -0
  11. package/src/components/bordered-box.ts +106 -0
  12. package/src/components/define-component.ts +33 -0
  13. package/src/components/index.ts +35 -0
  14. package/src/config.test.ts +469 -0
  15. package/src/config.ts +307 -0
  16. package/src/frame/box-frame.test.ts +44 -0
  17. package/src/frame/box-frame.ts +160 -0
  18. package/src/icons.ts +203 -0
  19. package/src/index.ts +359 -0
  20. package/src/runtime.ts +256 -0
  21. package/src/session-lifecycle.ts +41 -0
  22. package/src/state.test.ts +7 -0
  23. package/src/state.ts +90 -0
  24. package/src/telemetry.ts +301 -0
  25. package/src/ui/editor-tint.test.ts +70 -0
  26. package/src/ui/editor-tint.ts +78 -0
  27. package/src/ui/editor.ts +403 -0
  28. package/src/ui/footer.test.ts +350 -0
  29. package/src/ui/footer.ts +225 -0
  30. package/src/ui/header.test.ts +260 -0
  31. package/src/ui/header.ts +165 -0
  32. package/src/ui/preview.test.ts +639 -0
  33. package/src/ui/preview.ts +374 -0
  34. package/src/ui/render-helpers.ts +275 -0
  35. package/src/ui/settings-command.test.ts +218 -0
  36. package/src/ui/settings-command.ts +390 -0
  37. package/src/utils.ts +448 -0
  38. package/src/vim/editor-close-autocomplete.ts +26 -0
  39. package/src/vim/editor-host.test.ts +340 -0
  40. package/src/vim/editor-state.test.ts +385 -0
  41. package/src/vim/editor-state.ts +314 -0
  42. package/src/vim/mode-indicator.test.ts +27 -0
  43. package/src/vim/mode-indicator.ts +44 -0
  44. package/src/vim/selection-render.test.ts +77 -0
  45. package/src/vim/selection-render.ts +85 -0
  46. package/src/vim/text-model.test.ts +85 -0
  47. package/src/vim/text-model.ts +75 -0
  48. package/src/vim/vim-router.test.ts +50 -0
  49. package/src/vim/vim-router.ts +55 -0
  50. package/src/vim/word-motion.ts +96 -0
@@ -0,0 +1,218 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { Effect } from "effect";
3
+ import type { Theme } from "@earendil-works/pi-coding-agent";
4
+ import { DEFAULT_CONFIG, type TuiConfig } from "../config.ts";
5
+ import { VimRouter } from "../vim/vim-router.ts";
6
+ import { makeSettingsUi, type SettingsUiHandle } from "./settings-command.ts";
7
+
8
+ // Pass-through theme: selections and the active tab are detected via
9
+ // plain-text markers ("→ " prefix, "[Tab]" brackets) in the render output.
10
+ const theme = {
11
+ fg: (_color: string, text: string) => text,
12
+ bg: (_color: string, text: string) => text,
13
+ bold: (text: string) => text,
14
+ } as unknown as Theme;
15
+
16
+ const RENDER_WIDTH = 120;
17
+
18
+ // The settings UI injects an always-true gate for its own router instance
19
+ // (per-consumer gate injection), so its h/j/k/l stay unconditional regardless
20
+ // of the vim toggle.
21
+ const settingsRouter = Effect.runSync(
22
+ Effect.service(VimRouter).pipe(Effect.provide(VimRouter.make(() => true))),
23
+ );
24
+
25
+ interface UiSpy {
26
+ ui: SettingsUiHandle;
27
+ changes: TuiConfig[];
28
+ closes: number;
29
+ }
30
+
31
+ const makeUi = (overrides: Partial<TuiConfig> = {}): UiSpy => {
32
+ const spy: UiSpy = { ui: undefined!, changes: [], closes: 0 };
33
+ spy.ui = makeSettingsUi(
34
+ theme,
35
+ { ...structuredClone(DEFAULT_CONFIG), ...overrides },
36
+ (config) => {
37
+ spy.changes.push(config);
38
+ },
39
+ () => {
40
+ spy.closes += 1;
41
+ },
42
+ settingsRouter,
43
+ );
44
+ return spy;
45
+ };
46
+
47
+ const rendered = (ui: SettingsUiHandle): string[] => ui.render(RENDER_WIDTH);
48
+
49
+ const selectedShows = (ui: SettingsUiHandle, label: string): boolean =>
50
+ rendered(ui).some((line) => line.includes(`→ ${label}`));
51
+
52
+ const activeTab = (ui: SettingsUiHandle): string | undefined => {
53
+ const line = rendered(ui).find((l) => l.includes("["));
54
+ if (!line) return undefined;
55
+ for (const tab of ["General", "Icons", "Footer", "Telemetry"] as const) {
56
+ if (line.includes(`[${tab}]`)) return tab;
57
+ }
58
+ return undefined;
59
+ };
60
+
61
+ // ---------------------------------------------------------------------------
62
+ // Vim navigation: j/k move the list selection
63
+ // ---------------------------------------------------------------------------
64
+
65
+ it("starts with the first item of the features tab selected", () => {
66
+ const { ui } = makeUi();
67
+ assert.strictEqual(activeTab(ui), "General");
68
+ assert.strictEqual(selectedShows(ui, "Enabled"), true);
69
+ assert.strictEqual(selectedShows(ui, "Language"), false);
70
+ });
71
+
72
+ it("renders the Vim mode item on the features tab showing Off by default", () => {
73
+ const { ui } = makeUi();
74
+ const lines = rendered(ui);
75
+ assert.strictEqual(lines.some((line) => line.includes("Vim mode") && line.includes("Off")), true);
76
+ });
77
+
78
+ it("Space toggles vim on and reports the change", () => {
79
+ const { ui, changes } = makeUi();
80
+ ui.handleInput("j"); // move from Enabled to Vim mode
81
+ ui.handleInput(" ");
82
+ assert.strictEqual(changes.length, 1);
83
+ assert.strictEqual(changes[0]!.vim, true);
84
+ assert.strictEqual(changes[0]!.enabled, true); // other fields untouched
85
+ assert.strictEqual(rendered(ui).some((line) => line.includes("Vim mode") && line.includes("On")), true);
86
+ });
87
+
88
+ it("j moves the selection down and wraps to the first item at the end", () => {
89
+ const { ui } = makeUi();
90
+ ui.handleInput("j");
91
+ assert.strictEqual(selectedShows(ui, "Vim mode"), true);
92
+ ui.handleInput("j");
93
+ assert.strictEqual(selectedShows(ui, "Language"), true);
94
+ ui.handleInput("j");
95
+ assert.strictEqual(selectedShows(ui, "Enabled"), true);
96
+ });
97
+
98
+ it("k moves the selection up and wraps to the last item at the top", () => {
99
+ const { ui } = makeUi();
100
+ ui.handleInput("k");
101
+ assert.strictEqual(selectedShows(ui, "Language"), true);
102
+ ui.handleInput("k");
103
+ assert.strictEqual(selectedShows(ui, "Vim mode"), true);
104
+ ui.handleInput("k");
105
+ assert.strictEqual(selectedShows(ui, "Enabled"), true);
106
+ });
107
+
108
+ it("j moves the selection when vim is on too", () => {
109
+ const { ui } = makeUi({ vim: true });
110
+ ui.handleInput("j");
111
+ assert.strictEqual(selectedShows(ui, "Vim mode"), true);
112
+ ui.handleInput("j");
113
+ assert.strictEqual(selectedShows(ui, "Language"), true);
114
+ });
115
+
116
+ it("h switches tabs with vim off (settings gate is unconditional)", () => {
117
+ const { ui } = makeUi({ vim: false });
118
+ ui.handleInput("h");
119
+ assert.strictEqual(activeTab(ui), "Telemetry");
120
+ });
121
+
122
+ it("j moves the selection with vim off (settings gate is unconditional)", () => {
123
+ const { ui } = makeUi({ vim: false });
124
+ ui.handleInput("j");
125
+ assert.strictEqual(selectedShows(ui, "Vim mode"), true);
126
+ });
127
+
128
+ // ---------------------------------------------------------------------------
129
+ // Vim navigation: h/l switch tabs
130
+ // ---------------------------------------------------------------------------
131
+
132
+ it("l switches to the next tab and wraps from the last tab to the first", () => {
133
+ const { ui } = makeUi();
134
+ ui.handleInput("l");
135
+ assert.strictEqual(activeTab(ui), "Icons");
136
+ ui.handleInput("l");
137
+ assert.strictEqual(activeTab(ui), "Footer");
138
+ ui.handleInput("l");
139
+ assert.strictEqual(activeTab(ui), "Telemetry");
140
+ ui.handleInput("l");
141
+ assert.strictEqual(activeTab(ui), "General");
142
+ });
143
+
144
+ it("h switches to the previous tab and wraps from the first tab to the last", () => {
145
+ const { ui } = makeUi();
146
+ ui.handleInput("h");
147
+ assert.strictEqual(activeTab(ui), "Telemetry");
148
+ ui.handleInput("h");
149
+ assert.strictEqual(activeTab(ui), "Footer");
150
+ ui.handleInput("h");
151
+ assert.strictEqual(activeTab(ui), "Icons");
152
+ ui.handleInput("h");
153
+ assert.strictEqual(activeTab(ui), "General");
154
+ });
155
+
156
+ it("remembers the selected item per tab when navigating with h/l", () => {
157
+ const { ui } = makeUi();
158
+ ui.handleInput("j"); // features: Vim mode
159
+ ui.handleInput("j"); // features: Language
160
+ ui.handleInput("l"); // → Icons
161
+ ui.handleInput("h"); // → back to features
162
+ assert.strictEqual(selectedShows(ui, "Language"), true);
163
+ });
164
+
165
+ // ---------------------------------------------------------------------------
166
+ // Regression: arrow keys, Tab, Enter, and q still behave as before
167
+ // ---------------------------------------------------------------------------
168
+
169
+ it("the arrow keys still move the selection", () => {
170
+ const { ui } = makeUi();
171
+ ui.handleInput("\x1b[B"); // down
172
+ assert.strictEqual(selectedShows(ui, "Vim mode"), true);
173
+ ui.handleInput("\x1b[A"); // up
174
+ assert.strictEqual(selectedShows(ui, "Enabled"), true);
175
+ });
176
+
177
+ it("Tab and Shift+Tab still switch tabs", () => {
178
+ const { ui } = makeUi();
179
+ ui.handleInput("\t");
180
+ assert.strictEqual(activeTab(ui), "Icons");
181
+ ui.handleInput("\x1b[Z");
182
+ assert.strictEqual(activeTab(ui), "General");
183
+ });
184
+
185
+ it("j and k work on tabs with more items than fit the visible list", () => {
186
+ const { ui } = makeUi();
187
+ ui.handleInput("l");
188
+ ui.handleInput("l"); // → Footer (9 items)
189
+ ui.handleInput("k"); // wrap to the bottom of the segments list
190
+ assert.strictEqual(selectedShows(ui, "Extension status line"), true);
191
+ ui.handleInput("j"); // wrap to the top
192
+ assert.strictEqual(selectedShows(ui, "CWD"), true);
193
+ });
194
+
195
+ it("q and Escape close the settings UI", () => {
196
+ const spy = makeUi();
197
+ spy.ui.handleInput("q");
198
+ assert.strictEqual(spy.closes, 1);
199
+ spy.ui.handleInput("\x1b");
200
+ assert.strictEqual(spy.closes, 2);
201
+ });
202
+
203
+ it("Space still toggles the selected setting", () => {
204
+ const { ui, changes, closes } = makeUi();
205
+ ui.handleInput(" ");
206
+ assert.strictEqual(changes.length, 1);
207
+ assert.strictEqual(changes[0]!.enabled, false);
208
+ assert.strictEqual(closes, 0);
209
+ });
210
+
211
+ it("unrelated letters are ignored", () => {
212
+ const { ui, changes, closes } = makeUi();
213
+ ui.handleInput("x");
214
+ ui.handleInput("z");
215
+ assert.strictEqual(changes.length, 0);
216
+ assert.strictEqual(closes, 0);
217
+ assert.strictEqual(selectedShows(ui, "Enabled"), true);
218
+ });
@@ -0,0 +1,390 @@
1
+ import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ Container,
4
+ Key,
5
+ matchesKey,
6
+ SelectList,
7
+ type SelectItem,
8
+ type TUI,
9
+ Text,
10
+ } from "@earendil-works/pi-tui";
11
+ import { makeBorderedBox } from "../components/bordered-box.ts";
12
+ import type { IconMode, TuiConfig, SettingsLanguage } from "../config.ts";
13
+ import { VimRouter } from "../vim/vim-router.ts";
14
+
15
+ interface SettingItem {
16
+ id: string;
17
+ label: string;
18
+ currentValue: string;
19
+ }
20
+
21
+ type Tab = "features" | "icons" | "segments" | "telemetry";
22
+
23
+ const TABS: Tab[] = ["features", "icons", "segments", "telemetry"];
24
+
25
+ const COPY = {
26
+ en: {
27
+ title: "TUI Settings",
28
+ tabs: { features: "General", icons: "Icons", segments: "Footer", telemetry: "Telemetry" },
29
+ hint: "Tab/Shift+Tab/←/→/h/l: tabs · ↑/↓/j/k: move · Enter/Space: change · Esc/q: close",
30
+ labels: {
31
+ enabled: "Enabled",
32
+ vim: "Vim mode",
33
+ language: "Language",
34
+ iconMode: "Icon mode",
35
+ cwd: "CWD",
36
+ gitBranch: "Git branch",
37
+ gitStatus: "Git status",
38
+ gitCommit: "Git commit (detached)",
39
+ runtime: "Runtime",
40
+ context: "Context bar",
41
+ tokens: "Tokens",
42
+ cost: "Cost",
43
+ extensionStatuses: "Extension status line",
44
+ totalDuration: "Total duration",
45
+ tokenCounts: "Token counts",
46
+ stallDetails: "Stall details",
47
+ costRate: "Cost rate",
48
+ },
49
+ values: {
50
+ on: "On",
51
+ off: "Off",
52
+ languages: { en: "English" },
53
+ icons: { auto: "Auto", nerd: "Nerd", ascii: "ASCII" },
54
+ },
55
+ },
56
+ } as const;
57
+
58
+ type SettingsCopy = (typeof COPY)[SettingsLanguage];
59
+
60
+ function toggleSetting(config: TuiConfig, key: keyof TuiConfig["footerSegments"]): TuiConfig {
61
+ return {
62
+ ...config,
63
+ footerSegments: {
64
+ ...config.footerSegments,
65
+ [key]: !config.footerSegments[key],
66
+ },
67
+ };
68
+ }
69
+
70
+ function cycleIconMode(config: TuiConfig): TuiConfig {
71
+ const order: IconMode[] = ["auto", "nerd", "ascii"];
72
+ const currentIdx = order.indexOf(config.icons.mode);
73
+ const next = order[(currentIdx + 1) % order.length]!;
74
+ return { ...config, icons: { mode: next } };
75
+ }
76
+
77
+ function toggleEnabled(config: TuiConfig): TuiConfig {
78
+ return { ...config, enabled: !config.enabled };
79
+ }
80
+
81
+ function toggleVim(config: TuiConfig): TuiConfig {
82
+ return { ...config, vim: !config.vim };
83
+ }
84
+
85
+ function toggleLanguage(config: TuiConfig): TuiConfig {
86
+ return { ...config, settingsLanguage: config.settingsLanguage };
87
+ }
88
+
89
+ function toggleTelemetry(config: TuiConfig, key: keyof TuiConfig["telemetry"]): TuiConfig {
90
+ return {
91
+ ...config,
92
+ telemetry: { ...config.telemetry, [key]: !config.telemetry[key] },
93
+ };
94
+ }
95
+
96
+ function buildFeaturesItems(config: TuiConfig, copy: SettingsCopy): SettingItem[] {
97
+ return [
98
+ {
99
+ id: "enabled",
100
+ label: copy.labels.enabled,
101
+ currentValue: config.enabled ? copy.values.on : copy.values.off,
102
+ },
103
+ {
104
+ id: "vim",
105
+ label: copy.labels.vim,
106
+ currentValue: config.vim ? copy.values.on : copy.values.off,
107
+ },
108
+ {
109
+ id: "settingsLanguage",
110
+ label: copy.labels.language,
111
+ currentValue: copy.values.languages[config.settingsLanguage],
112
+ },
113
+ ];
114
+ }
115
+
116
+ function buildIconsItems(config: TuiConfig, copy: SettingsCopy): SettingItem[] {
117
+ return [
118
+ { id: "mode", label: copy.labels.iconMode, currentValue: copy.values.icons[config.icons.mode] },
119
+ ];
120
+ }
121
+
122
+ function buildSegmentsItems(config: TuiConfig, copy: SettingsCopy): SettingItem[] {
123
+ const segs = config.footerSegments;
124
+ const flag = (value: boolean) => (value ? copy.values.on : copy.values.off);
125
+ return [
126
+ { id: "cwd", label: copy.labels.cwd, currentValue: flag(segs.cwd) },
127
+ { id: "gitBranch", label: copy.labels.gitBranch, currentValue: flag(segs.gitBranch) },
128
+ { id: "gitStatus", label: copy.labels.gitStatus, currentValue: flag(segs.gitStatus) },
129
+ { id: "gitCommit", label: copy.labels.gitCommit, currentValue: flag(segs.gitCommit) },
130
+ { id: "runtime", label: copy.labels.runtime, currentValue: flag(segs.runtime) },
131
+ { id: "context", label: copy.labels.context, currentValue: flag(segs.context) },
132
+ { id: "tokens", label: copy.labels.tokens, currentValue: flag(segs.tokens) },
133
+ { id: "cost", label: copy.labels.cost, currentValue: flag(segs.cost) },
134
+ {
135
+ id: "extensionStatuses",
136
+ label: copy.labels.extensionStatuses,
137
+ currentValue: flag(segs.extensionStatuses),
138
+ },
139
+ ];
140
+ }
141
+
142
+ function buildTelemetryItems(config: TuiConfig, copy: SettingsCopy): SettingItem[] {
143
+ const telemetry = config.telemetry;
144
+ const flag = (value: boolean) => (value ? copy.values.on : copy.values.off);
145
+ return [
146
+ { id: "enabled", label: copy.labels.enabled, currentValue: flag(telemetry.enabled) },
147
+ { id: "tps", label: "TPS", currentValue: flag(telemetry.tps) },
148
+ { id: "ttft", label: "TTFT", currentValue: flag(telemetry.ttft) },
149
+ { id: "duration", label: copy.labels.totalDuration, currentValue: flag(telemetry.duration) },
150
+ { id: "tokens", label: copy.labels.tokenCounts, currentValue: flag(telemetry.tokens) },
151
+ { id: "stalls", label: copy.labels.stallDetails, currentValue: flag(telemetry.stalls) },
152
+ { id: "cost", label: copy.labels.costRate, currentValue: flag(telemetry.cost) },
153
+ ];
154
+ }
155
+
156
+ function buildItems(tab: Tab, config: TuiConfig): SettingItem[] {
157
+ const copy = COPY[config.settingsLanguage];
158
+ switch (tab) {
159
+ case "features":
160
+ return buildFeaturesItems(config, copy);
161
+ case "icons":
162
+ return buildIconsItems(config, copy);
163
+ case "segments":
164
+ return buildSegmentsItems(config, copy);
165
+ case "telemetry":
166
+ return buildTelemetryItems(config, copy);
167
+ }
168
+ }
169
+
170
+ function handleSettingChange(tab: Tab, itemId: string, config: TuiConfig): TuiConfig {
171
+ if (tab === "features") {
172
+ if (itemId === "enabled") return toggleEnabled(config);
173
+ if (itemId === "vim") return toggleVim(config);
174
+ if (itemId === "settingsLanguage") return toggleLanguage(config);
175
+ }
176
+ if (tab === "icons" && itemId === "mode") return cycleIconMode(config);
177
+ if (tab === "segments") {
178
+ return toggleSetting(config, itemId as keyof TuiConfig["footerSegments"]);
179
+ }
180
+ if (tab === "telemetry") {
181
+ return toggleTelemetry(config, itemId as keyof TuiConfig["telemetry"]);
182
+ }
183
+ return config;
184
+ }
185
+
186
+ export interface SettingsUiHandle {
187
+ render: (width: number) => string[];
188
+ invalidate: () => void;
189
+ handleInput: (data: string) => void;
190
+ }
191
+
192
+ /**
193
+ * Settings dialog for the tui extension (`/tui` command): tabbed list of
194
+ * feature/icon/footer/telemetry switches, framed in the house rounded box.
195
+ *
196
+ * Closure factory: all mutable state (tab, config, selection, render cache)
197
+ * lives in the factory closure, so the returned handle uses no `this` and
198
+ * survives any wrapper-style hand-off into pi.
199
+ */
200
+ export const makeSettingsUi = (
201
+ theme: Theme,
202
+ config: TuiConfig,
203
+ onChange: (config: TuiConfig) => void,
204
+ onClose: () => void,
205
+ router: VimRouter["Service"],
206
+ ): SettingsUiHandle => {
207
+ let tab: Tab = "features";
208
+ let currentConfig = config;
209
+ let selectList!: SelectList;
210
+ let bordered!: ReturnType<typeof makeBorderedBox>;
211
+ const selectedItemByTab: Partial<Record<Tab, string>> = {};
212
+ const body = new Container();
213
+ let cachedWidth: number | undefined;
214
+ let cachedLines: string[] | undefined;
215
+ let compact = false;
216
+
217
+ const applySetting = (itemId: string): void => {
218
+ selectedItemByTab[tab] = itemId;
219
+ currentConfig = handleSettingChange(tab, itemId, currentConfig);
220
+ onChange(currentConfig);
221
+ rebuild(itemId);
222
+ };
223
+
224
+ const switchTab = (offset: number): void => {
225
+ const idx = TABS.indexOf(tab);
226
+ tab = TABS[(idx + offset + TABS.length) % TABS.length]!;
227
+ rebuild();
228
+ };
229
+
230
+ const rebuild = (preferredItemId = selectedItemByTab[tab]): void => {
231
+ const copy = COPY[currentConfig.settingsLanguage];
232
+ body.clear();
233
+
234
+ const tabBar = TABS.map((tabName) => {
235
+ const active = tabName === tab;
236
+ const label = active ? `[${copy.tabs[tabName]}]` : ` ${copy.tabs[tabName]} `;
237
+ return active ? theme.fg("accent", label) : theme.fg("dim", label);
238
+ }).join(" ");
239
+ body.addChild(new Text(tabBar, 0, 0));
240
+ body.addChild(new Text(theme.fg("dim", copy.hint), 0, 0));
241
+
242
+ const items = buildItems(tab, currentConfig).map(
243
+ (item) =>
244
+ ({
245
+ value: item.id,
246
+ label: compact ? `${item.label}: ${item.currentValue}` : item.label,
247
+ description: compact ? undefined : item.currentValue,
248
+ }) as SelectItem,
249
+ );
250
+ selectList = new SelectList(items, Math.min(items.length, 10), {
251
+ selectedPrefix: (t) => theme.fg("accent", t),
252
+ selectedText: (t) => theme.fg("accent", t),
253
+ description: (t) => theme.fg("muted", t),
254
+ scrollInfo: (t) => theme.fg("dim", t),
255
+ noMatch: (t) => theme.fg("warning", t),
256
+ });
257
+ const selectedIndex = items.findIndex((item) => item.value === preferredItemId);
258
+ if (selectedIndex >= 0) {
259
+ selectList.setSelectedIndex(selectedIndex);
260
+ }
261
+ selectedItemByTab[tab] = selectList.getSelectedItem()?.value;
262
+ selectList.onSelectionChange = (item) => {
263
+ selectedItemByTab[tab] = item.value;
264
+ };
265
+ selectList.onSelect = (item) => {
266
+ applySetting(item.value);
267
+ };
268
+ selectList.onCancel = () => {
269
+ onClose();
270
+ };
271
+ body.addChild(selectList);
272
+
273
+ bordered = makeBorderedBox(body, theme, {
274
+ label: theme.bold(theme.fg("accent", copy.title)),
275
+ bg: (s: string) => theme.bg("customMessageBg", s),
276
+ });
277
+ cachedWidth = undefined;
278
+ cachedLines = undefined;
279
+ };
280
+
281
+ /**
282
+ * Move the list selection by `offset` items, wrapping around at both ends.
283
+ * This is the consumer that maps a router navigation intent onto the
284
+ * widget's own cursor/wrap state. The settings UI injects an always-true
285
+ * gate for its own router instance, so j/k drive this unconditionally
286
+ * (h/l drive switchTab) with or without the vim toggle.
287
+ */
288
+ const moveSelection = (offset: number): void => {
289
+ const items = buildItems(tab, currentConfig);
290
+ if (items.length === 0) return;
291
+ const currentIndex = items.findIndex((item) => item.id === selectList.getSelectedItem()?.value);
292
+ const nextIndex = (currentIndex + offset + items.length) % items.length;
293
+ selectList.setSelectedIndex(nextIndex);
294
+ const item = items[nextIndex];
295
+ if (item) selectedItemByTab[tab] = item.id;
296
+ };
297
+
298
+ const handleInput = (data: string): void => {
299
+ const intent = router.decodeNavigation(data);
300
+ if (intent?.kind === "move") {
301
+ if (intent.dir === "down") moveSelection(1);
302
+ else if (intent.dir === "up") moveSelection(-1);
303
+ else if (intent.dir === "right") switchTab(1);
304
+ else if (intent.dir === "left") switchTab(-1);
305
+ invalidate();
306
+ return;
307
+ }
308
+ if (matchesKey(data, Key.tab) || matchesKey(data, Key.right)) {
309
+ switchTab(1);
310
+ invalidate();
311
+ return;
312
+ }
313
+ if (matchesKey(data, Key.shift("tab")) || matchesKey(data, Key.left)) {
314
+ switchTab(-1);
315
+ invalidate();
316
+ return;
317
+ }
318
+ if (matchesKey(data, Key.escape) || matchesKey(data, "q")) {
319
+ onClose();
320
+ return;
321
+ }
322
+ if (matchesKey(data, Key.space) || data === " ") {
323
+ const selected = selectList.getSelectedItem();
324
+ if (selected) applySetting(selected.value);
325
+ } else {
326
+ selectList.handleInput?.(data);
327
+ }
328
+ invalidate();
329
+ };
330
+
331
+ const render = (width: number): string[] => {
332
+ // The body renders at contentWidth = width - 4 (2 rails + 2×paddingX),
333
+ // mirroring makeBorderedBox's default paddingX of 1.
334
+ const widthCompact = Math.max(1, width - 4) <= 60;
335
+ if (widthCompact !== compact) {
336
+ compact = widthCompact;
337
+ rebuild();
338
+ }
339
+ if (cachedLines && cachedWidth === width) return cachedLines;
340
+ cachedWidth = width;
341
+ cachedLines = bordered.render(width);
342
+ return cachedLines;
343
+ };
344
+
345
+ const invalidate = (): void => {
346
+ cachedWidth = undefined;
347
+ cachedLines = undefined;
348
+ bordered.invalidate();
349
+ };
350
+
351
+ rebuild();
352
+
353
+ return { render, invalidate, handleInput };
354
+ };
355
+
356
+ export function registerSettingsCommand(
357
+ pi: ExtensionAPI,
358
+ hooks: {
359
+ getConfig: () => TuiConfig;
360
+ onConfigChanged: (config: TuiConfig) => void;
361
+ },
362
+ router: VimRouter["Service"],
363
+ ): void {
364
+ pi.registerCommand("tui", {
365
+ description: "Open the tui settings UI",
366
+ handler: async (_args, ctx: ExtensionContext) => {
367
+ if (!ctx.hasUI) return;
368
+ await ctx.ui.custom<void>(
369
+ (tui: TUI, theme, _kb, done) => {
370
+ const ui = makeSettingsUi(
371
+ theme,
372
+ hooks.getConfig(),
373
+ (config) => hooks.onConfigChanged(config),
374
+ () => done(undefined),
375
+ router,
376
+ );
377
+ return {
378
+ render: (w: number) => ui.render(w),
379
+ invalidate: () => ui.invalidate(),
380
+ handleInput: (data: string) => {
381
+ ui.handleInput(data);
382
+ tui.requestRender();
383
+ },
384
+ };
385
+ },
386
+ { overlay: true },
387
+ );
388
+ },
389
+ });
390
+ }