@narumitw/pi-statusline 0.49.0 → 0.49.3

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/src/commands.ts DELETED
@@ -1,929 +0,0 @@
1
- import {
2
- DynamicBorder,
3
- type ExtensionAPI,
4
- type ExtensionCommandContext,
5
- } from "@earendil-works/pi-coding-agent";
6
- import {
7
- type AutocompleteItem,
8
- Container,
9
- Key,
10
- matchesKey,
11
- type SelectItem,
12
- SelectList,
13
- Text,
14
- truncateToWidth,
15
- wrapTextWithAnsi,
16
- } from "@earendil-works/pi-tui";
17
- import {
18
- INFORMATION_PROFILE_NAMES,
19
- INFORMATION_PROFILES,
20
- type InformationProfileName,
21
- inferInformationProfile,
22
- } from "./information-profiles.js";
23
- import { segmentPaletteForPreset } from "./presets/index.js";
24
- import {
25
- DEFAULT_STATUSLINE_DOCUMENT,
26
- type LoadedStatuslineSettings,
27
- removeStatuslineSettingsDocumentIfMatches,
28
- saveStatuslineSettingsDocument,
29
- } from "./settings.js";
30
- import {
31
- type ConfigSegmentName,
32
- LINE_BREAK_SEGMENT_NAME,
33
- PALETTE_NAMES,
34
- PALETTE_PRESET_NAMES,
35
- type PaletteName,
36
- type PalettePreset,
37
- SEGMENT_NAMES,
38
- type SegmentName,
39
- } from "./types.js";
40
-
41
- const EDIT_SETTINGS_LABEL = "Edit settings JSON";
42
- const SEGMENT_VIEWPORT_SIZE = 6;
43
- const NARROW_SEGMENT_VIEWPORT_SIZE = 3;
44
- const SEGMENT_DESCRIPTIONS: Record<SegmentName, string> = {
45
- brand: "Pi brand mark",
46
- provider: "Current model provider",
47
- model: "Current model name",
48
- thinking: "Current thinking level",
49
- cwd: "Current working directory",
50
- branch: "Git branch, status, and linked pull request",
51
- tools: "Current tool and streaming activity",
52
- context: "Current context-window usage",
53
- tokens: "Session token totals",
54
- cache: "Prompt-cache reads, writes, and latest hit rate",
55
- cost: "Session cost",
56
- time: "Current local time",
57
- turn: "Current session turn count",
58
- };
59
- const SUBCOMMANDS: AutocompleteItem[] = [
60
- { value: "settings", label: "settings", description: "Edit pi-statusline.json" },
61
- { value: "status", label: "status", description: "Show effective statusline settings" },
62
- { value: "help", label: "help", description: "Show configuration help" },
63
- ];
64
-
65
- export interface StatuslineCommandOptions {
66
- settingsPath: string;
67
- getLoaded(): LoadedStatuslineSettings;
68
- apply(loaded: LoadedStatuslineSettings, ctx: ExtensionCommandContext): void;
69
- preview?(palettePreset: PalettePreset | undefined, ctx: ExtensionCommandContext): void;
70
- save?: (settingsPath: string, rawDocument: string) => LoadedStatuslineSettings;
71
- getMenuOwner?(): { signal: AbortSignal; isCurrent(): boolean };
72
- }
73
-
74
- export function registerStatuslineCommand(pi: ExtensionAPI, options: StatuslineCommandOptions) {
75
- pi.registerCommand("statusline", {
76
- description: "Open or inspect the statusline settings",
77
- getArgumentCompletions(prefix: string): AutocompleteItem[] | null {
78
- const normalized = prefix.trim().toLowerCase();
79
- const matches = SUBCOMMANDS.filter((item) => item.value.startsWith(normalized));
80
- return matches.length > 0 ? matches : null;
81
- },
82
- handler: async (args, ctx) => {
83
- const normalized = args.trim();
84
- if (!normalized) {
85
- await showMainMenu(ctx, options);
86
- return;
87
- }
88
-
89
- const tokens = normalized.split(/\s+/u);
90
- const subcommand = tokens[0]?.toLowerCase() ?? "";
91
- if (tokens.length > 1) {
92
- if (canNotify(ctx)) {
93
- ctx.ui.notify(`/statusline ${subcommand} does not accept trailing arguments.`, "warning");
94
- }
95
- return;
96
- }
97
-
98
- switch (subcommand) {
99
- case "settings":
100
- await editSettings(ctx, options);
101
- return;
102
- case "status":
103
- showStatus(ctx, options);
104
- return;
105
- case "help":
106
- showHelp(ctx, options.settingsPath);
107
- return;
108
- default:
109
- if (canNotify(ctx)) {
110
- ctx.ui.notify(`Unknown /statusline subcommand: ${subcommand}`, "warning");
111
- }
112
- }
113
- },
114
- });
115
- }
116
-
117
- async function showMainMenu(ctx: ExtensionCommandContext, options: StatuslineCommandOptions) {
118
- if (ctx.mode !== "tui") {
119
- if (ctx.hasUI) ctx.ui.notify("/statusline requires an interactive Pi UI in TUI mode.", "error");
120
- return;
121
- }
122
- const fallbackController = new AbortController();
123
- const owner = options.getMenuOwner?.() ?? {
124
- signal: fallbackController.signal,
125
- isCurrent: () => !fallbackController.signal.aborted,
126
- };
127
- const { defineMenu, runMenu } = await import("@narumitw/pi-tui-kit");
128
- if (owner.signal.aborted || !owner.isCurrent()) return;
129
- type Screen = "main" | "advanced" | "information";
130
- type Action = "appearance" | "setInformation" | "layout" | "edit" | "status" | "help" | "back";
131
- const menu = defineMenu<undefined, Screen, Action, ExtensionCommandContext>({
132
- start: "main",
133
- screens: {
134
- main: () => {
135
- const config = options.getLoaded().config;
136
- return {
137
- kind: "actions",
138
- title: "pi-statusline",
139
- items: [
140
- {
141
- id: "appearance",
142
- label: `Appearance (${config.palettePreset})`,
143
- action: "appearance",
144
- },
145
- {
146
- id: "information",
147
- label: `Information (${inferInformationProfile(config.segments)})`,
148
- to: "information",
149
- },
150
- { id: "advanced", label: "Advanced", to: "advanced" },
151
- { id: "status", label: "Status", action: "status" },
152
- { id: "help", label: "Help", action: "help" },
153
- ],
154
- hint: "close",
155
- };
156
- },
157
- information: () => {
158
- const current = inferInformationProfile(options.getLoaded().config.segments);
159
- return {
160
- kind: "choice",
161
- title: "Information level",
162
- lines: [`Current profile: ${current}`],
163
- items: INFORMATION_PROFILE_NAMES.map((profile) => ({
164
- id: profile,
165
- label: `${profile[0]?.toUpperCase() ?? ""}${profile.slice(1)}`,
166
- description: `${INFORMATION_PROFILES[profile].length} segments`,
167
- details: [`Segments: ${INFORMATION_PROFILES[profile].join(" · ")}`],
168
- })),
169
- action: "setInformation",
170
- currentItemId: current,
171
- initialItemId: current === "custom" ? "balanced" : current,
172
- hint: "close",
173
- };
174
- },
175
- advanced: () => {
176
- const config = options.getLoaded().config;
177
- const visibleSegmentCount = config.segments.filter(
178
- (segment): segment is SegmentName => segment !== LINE_BREAK_SEGMENT_NAME,
179
- ).length;
180
- return {
181
- kind: "actions",
182
- title: "pi-statusline — Advanced",
183
- items: [
184
- {
185
- id: "layout",
186
- label: `Custom layout (${visibleSegmentCount}/${SEGMENT_NAMES.length} shown)`,
187
- action: "layout",
188
- },
189
- { id: "edit", label: EDIT_SETTINGS_LABEL, action: "edit" },
190
- { id: "back", label: "Back", action: "back" },
191
- ],
192
- hint: "back",
193
- };
194
- },
195
- },
196
- actions: {
197
- appearance: async () => {
198
- await choosePalettePreset(ctx, options);
199
- return { kind: "close" };
200
- },
201
- setInformation: async ({ itemId }) => {
202
- const profile = INFORMATION_PROFILE_NAMES.find((candidate) => candidate === itemId);
203
- if (!profile) return { kind: "rejected" };
204
- applyInformationProfile(ctx, options, profile);
205
- return { kind: "close" };
206
- },
207
- layout: async () => {
208
- await chooseSegments(ctx, options);
209
- return { kind: "close" };
210
- },
211
- edit: async () => {
212
- await editSettings(ctx, options);
213
- return { kind: "close" };
214
- },
215
- status: async () => {
216
- showStatus(ctx, options);
217
- return { kind: "close" };
218
- },
219
- help: async () => {
220
- showHelp(ctx, options.settingsPath);
221
- return { kind: "close" };
222
- },
223
- back: async () => ({ kind: "back" }),
224
- },
225
- });
226
- try {
227
- await runMenu(ctx, menu, {
228
- getState: () => undefined,
229
- signal: owner.signal,
230
- isCurrent: owner.isCurrent,
231
- });
232
- } finally {
233
- fallbackController.abort(new DOMException("Statusline menu closed", "AbortError"));
234
- }
235
- }
236
-
237
- async function choosePalettePreset(
238
- ctx: ExtensionCommandContext,
239
- options: StatuslineCommandOptions,
240
- ) {
241
- if (ctx.mode !== "tui") {
242
- if (ctx.hasUI) ctx.ui.notify(`Edit palettePreset manually: ${options.settingsPath}`, "info");
243
- return;
244
- }
245
- const current = options.getLoaded();
246
- let selection: PalettePreset | undefined;
247
- try {
248
- selection = await showPalettePresetPicker(ctx, current.config.palettePreset, options);
249
- } finally {
250
- options.preview?.(undefined, ctx);
251
- }
252
- if (selection === undefined) return;
253
-
254
- let loaded: LoadedStatuslineSettings;
255
- try {
256
- const rawDocument = palettePresetDocument(current, selection);
257
- loaded = (options.save ?? saveStatuslineSettingsDocument)(options.settingsPath, rawDocument);
258
- } catch (error) {
259
- ctx.ui.notify(`Palette preset was not saved: ${formatError(error)}`, "error");
260
- return;
261
- }
262
- try {
263
- options.apply(loaded, ctx);
264
- } catch (error) {
265
- const rollbackError = restoreStatuslineSettings(ctx, options, current, loaded);
266
- ctx.ui.notify(
267
- rollbackError
268
- ? `Palette preset could not be applied: ${formatError(error)}; rollback failed: ${formatError(rollbackError)}`
269
- : `Palette preset could not be applied: ${formatError(error)}; previous settings restored.`,
270
- "error",
271
- );
272
- return;
273
- }
274
- const message =
275
- loaded.config.palettePreset === "custom"
276
- ? "Custom palette applied. Edit colors via /statusline → Advanced → Edit settings JSON."
277
- : `Palette preset applied: ${loaded.config.palettePreset}.`;
278
- ctx.ui.notify(message, "info");
279
- }
280
-
281
- async function showPalettePresetPicker(
282
- ctx: ExtensionCommandContext,
283
- current: PalettePreset,
284
- options: StatuslineCommandOptions,
285
- ): Promise<PalettePreset | undefined> {
286
- const items: SelectItem[] = PALETTE_PRESET_NAMES.map((palettePreset) => ({
287
- value: palettePreset,
288
- label: palettePreset,
289
- description:
290
- [
291
- palettePreset === current ? "current" : undefined,
292
- palettePreset === "custom" ? "per-segment colors from settings JSON" : undefined,
293
- ]
294
- .filter((part): part is string => part !== undefined)
295
- .join(" • ") || undefined,
296
- }));
297
- const selectedIndex = PALETTE_PRESET_NAMES.indexOf(current);
298
- const result = await ctx.ui.custom<PalettePreset | null>((tui, theme, _keybindings, done) => {
299
- const container = new Container();
300
- container.addChild(new DynamicBorder((text: string) => theme.fg("accent", text)));
301
- const title = new Text("", 1, 0);
302
- container.addChild(title);
303
- const list = new SelectList(items, Math.min(items.length, 10), {
304
- selectedPrefix: (text) => theme.fg("accent", text),
305
- selectedText: (text) => theme.fg("accent", text),
306
- description: (text) => theme.fg("muted", text),
307
- scrollInfo: (text) => theme.fg("dim", text),
308
- noMatch: (text) => theme.fg("warning", text),
309
- });
310
- list.setSelectedIndex(selectedIndex);
311
- list.onSelectionChange = (item) => {
312
- options.preview?.(item.value as PalettePreset, ctx);
313
- };
314
- list.onSelect = (item) => done(item.value as PalettePreset);
315
- list.onCancel = () => done(null);
316
- container.addChild(list);
317
- const hint = new Text("", 1, 0);
318
- container.addChild(hint);
319
- container.addChild(new DynamicBorder((text: string) => theme.fg("accent", text)));
320
- const updateThemedText = () => {
321
- title.setText(theme.fg("accent", theme.bold(`Palette preset (current: ${current})`)));
322
- hint.setText(theme.fg("dim", "↑↓ preview • enter apply • esc cancel"));
323
- };
324
- updateThemedText();
325
-
326
- return {
327
- render: (width: number) => container.render(width),
328
- invalidate() {
329
- container.invalidate();
330
- updateThemedText();
331
- },
332
- handleInput(data: string) {
333
- list.handleInput(data);
334
- tui.requestRender();
335
- },
336
- };
337
- });
338
- return result ?? undefined;
339
- }
340
-
341
- function applyInformationProfile(
342
- ctx: ExtensionCommandContext,
343
- options: StatuslineCommandOptions,
344
- selection: InformationProfileName,
345
- ) {
346
- const current = options.getLoaded();
347
- try {
348
- const change = informationProfileDocument(current, selection);
349
- const loaded = applySegmentsDocumentChange(change, ctx, options);
350
- ctx.ui.notify(
351
- `Information level applied: ${inferInformationProfile(loaded.config.segments)}.`,
352
- "info",
353
- );
354
- } catch (error) {
355
- ctx.ui.notify(`Information level was not saved: ${formatError(error)}`, "error");
356
- }
357
- }
358
-
359
- async function chooseSegments(ctx: ExtensionCommandContext, options: StatuslineCommandOptions) {
360
- if (ctx.mode !== "tui") {
361
- if (ctx.hasUI) ctx.ui.notify(`Edit segments manually: ${options.settingsPath}`, "info");
362
- return;
363
- }
364
- let current = options.getLoaded();
365
- let names = segmentMenuOrder(current);
366
- let selectedIndex = 0;
367
- let moveMode = false;
368
- let feedback: string | undefined;
369
-
370
- await ctx.ui.custom((tui, theme, keybindings, done) => {
371
- const commit = (
372
- name: SegmentName,
373
- change: { nextDocument: string; previousDocument: string },
374
- ): boolean => {
375
- try {
376
- current = applySegmentsDocumentChange(change, ctx, options);
377
- names = segmentMenuOrder(current);
378
- selectedIndex = Math.max(0, names.indexOf(name));
379
- feedback = undefined;
380
- return true;
381
- } catch (error) {
382
- ctx.ui.notify(`Statusline segments were not saved: ${formatError(error)}`, "error");
383
- return false;
384
- }
385
- };
386
-
387
- const toggleSelected = () => {
388
- const name = names[selectedIndex];
389
- if (!name) return;
390
- moveMode = false;
391
- commit(name, segmentsDocument(current, name, !current.config.segments.includes(name)));
392
- };
393
-
394
- const toggleLineBreakAfterSelected = () => {
395
- const name = names[selectedIndex];
396
- if (!name) return;
397
- moveMode = false;
398
- const segmentIndex = current.config.segments.indexOf(name);
399
- if (segmentIndex < 0) {
400
- feedback = `Show ${name} before adding a line break.`;
401
- return;
402
- }
403
- const hasLineBreak = current.config.segments[segmentIndex + 1] === LINE_BREAK_SEGMENT_NAME;
404
- const hasFollowingSegment = current.config.segments
405
- .slice(segmentIndex + 1)
406
- .some((segment) => segment !== LINE_BREAK_SEGMENT_NAME);
407
- if (!hasLineBreak && !hasFollowingSegment) {
408
- feedback = `Add another visible segment after ${name} before adding a line break.`;
409
- return;
410
- }
411
- commit(name, lineBreakAfterDocument(current, name));
412
- };
413
-
414
- const reorderSelected = (direction: -1 | 1) => {
415
- const name = names[selectedIndex];
416
- if (!name) return;
417
- const visibleNames = visibleSegmentNames(current);
418
- const currentIndex = visibleNames.indexOf(name);
419
- if (currentIndex < 0) {
420
- feedback = `Show ${name} before moving it.`;
421
- return;
422
- }
423
- const targetIndex = currentIndex + direction;
424
- if (targetIndex < 0 || targetIndex >= visibleNames.length) {
425
- feedback = `${name} is already the ${direction < 0 ? "first" : "last"} visible segment.`;
426
- return;
427
- }
428
- const change = reorderedSegmentsDocument(current, name, direction);
429
- if (change) commit(name, change);
430
- };
431
-
432
- const enterMoveMode = () => {
433
- const name = names[selectedIndex];
434
- if (!name) return;
435
- if (!current.config.segments.includes(name)) {
436
- feedback = `Show ${name} before moving it.`;
437
- return;
438
- }
439
- moveMode = true;
440
- feedback = undefined;
441
- };
442
-
443
- const moveSelection = (offset: number) => {
444
- selectedIndex = Math.max(0, Math.min(names.length - 1, selectedIndex + offset));
445
- feedback = undefined;
446
- };
447
-
448
- const renderList = (width: number): string[] => {
449
- const safeWidth = Math.max(1, width);
450
- const visibleNames = visibleSegmentNames(current);
451
- const visible = new Set(visibleNames);
452
- const placements = segmentPlacements(current.config.segments);
453
- const viewportSize = safeWidth < 30 ? NARROW_SEGMENT_VIEWPORT_SIZE : SEGMENT_VIEWPORT_SIZE;
454
- const startIndex = Math.max(
455
- 0,
456
- Math.min(
457
- selectedIndex - Math.floor(viewportSize / 2),
458
- Math.max(0, names.length - viewportSize),
459
- ),
460
- );
461
- const endIndex = Math.min(names.length, startIndex + viewportSize);
462
- const lines: string[] = [];
463
- let previousSection: "visible" | "hidden" | undefined;
464
- for (let index = startIndex; index < endIndex; index += 1) {
465
- const name = names[index];
466
- if (!name) continue;
467
- const section = visible.has(name) ? "visible" : "hidden";
468
- if (section !== previousSection) {
469
- const heading =
470
- section === "visible" ? "Visible — render order" : "Hidden — not rendered";
471
- lines.push(theme.fg("muted", theme.bold(truncateToWidth(` ${heading}`, safeWidth))));
472
- previousSection = section;
473
- }
474
- const isSelected = index === selectedIndex;
475
- const prefix = isSelected ? "→ " : " ";
476
- const placement = placements.get(name);
477
- const lineBreakLabel = hasLineBreakAfter(current.config.segments, name)
478
- ? " · break after"
479
- : "";
480
- const row = placement
481
- ? `${prefix}${`${placement.order}.`.padStart(3)} row ${placement.row} · ${name.padEnd(8)} · visible${lineBreakLabel}`
482
- : `${prefix} · ${name.padEnd(8)} · hidden`;
483
- const truncated = truncateToWidth(row, safeWidth);
484
- if (isSelected) lines.push(theme.fg("accent", truncated));
485
- else lines.push(section === "visible" ? truncated : theme.fg("muted", truncated));
486
- }
487
- if (startIndex > 0 || endIndex < names.length) {
488
- lines.push(
489
- theme.fg(
490
- "dim",
491
- truncateToWidth(` (${startIndex + 1}-${endIndex}/${names.length})`, safeWidth),
492
- ),
493
- );
494
- }
495
-
496
- const selected = names[selectedIndex];
497
- if (selected) {
498
- lines.push("");
499
- const detail = feedback ?? SEGMENT_DESCRIPTIONS[selected];
500
- const color = feedback ? "warning" : "muted";
501
- for (const line of wrapTextWithAnsi(detail, Math.max(1, safeWidth - 2))) {
502
- lines.push(theme.fg(color, truncateToWidth(` ${line}`, safeWidth)));
503
- }
504
- }
505
-
506
- lines.push("");
507
- const hints = segmentControlHints(safeWidth, moveMode, selected);
508
- for (const hint of hints) {
509
- lines.push(theme.fg("dim", truncateToWidth(` ${hint}`, safeWidth)));
510
- }
511
- return lines;
512
- };
513
-
514
- const container = new Container();
515
- container.addChild(new DynamicBorder((text: string) => theme.fg("accent", text)));
516
- const title = new Text("", 1, 0);
517
- container.addChild(title);
518
- container.addChild({ render: renderList, invalidate() {} });
519
- container.addChild(new DynamicBorder((text: string) => theme.fg("accent", text)));
520
- const updateThemedText = () => {
521
- title.setText(theme.fg("accent", theme.bold("Statusline segments")));
522
- };
523
- updateThemedText();
524
-
525
- return {
526
- render: (width: number) => container.render(width),
527
- invalidate() {
528
- container.invalidate();
529
- updateThemedText();
530
- },
531
- handleInput(data: string) {
532
- const moveModeKey = matchesKey(data, "m") || matchesKey(data, Key.shift("m"));
533
- const lineBreakKey = matchesKey(data, "b") || matchesKey(data, Key.shift("b"));
534
- if (matchesKey(data, Key.alt("up"))) {
535
- reorderSelected(-1);
536
- } else if (matchesKey(data, Key.alt("down"))) {
537
- reorderSelected(1);
538
- } else if (moveMode) {
539
- if (keybindings.matches(data, "tui.select.up")) {
540
- reorderSelected(-1);
541
- } else if (keybindings.matches(data, "tui.select.down")) {
542
- reorderSelected(1);
543
- } else if (
544
- moveModeKey ||
545
- keybindings.matches(data, "tui.select.confirm") ||
546
- data === " " ||
547
- keybindings.matches(data, "tui.select.cancel")
548
- ) {
549
- moveMode = false;
550
- feedback = undefined;
551
- }
552
- } else if (keybindings.matches(data, "tui.select.up")) {
553
- selectedIndex = selectedIndex === 0 ? names.length - 1 : selectedIndex - 1;
554
- feedback = undefined;
555
- } else if (keybindings.matches(data, "tui.select.down")) {
556
- selectedIndex = selectedIndex === names.length - 1 ? 0 : selectedIndex + 1;
557
- feedback = undefined;
558
- } else if (keybindings.matches(data, "tui.select.pageUp")) {
559
- moveSelection(-SEGMENT_VIEWPORT_SIZE);
560
- } else if (keybindings.matches(data, "tui.select.pageDown")) {
561
- moveSelection(SEGMENT_VIEWPORT_SIZE);
562
- } else if (moveModeKey) {
563
- enterMoveMode();
564
- } else if (lineBreakKey) {
565
- toggleLineBreakAfterSelected();
566
- } else if (keybindings.matches(data, "tui.select.confirm") || data === " ") {
567
- toggleSelected();
568
- } else if (keybindings.matches(data, "tui.select.cancel")) {
569
- done(undefined);
570
- }
571
- tui.requestRender();
572
- },
573
- };
574
- });
575
- }
576
-
577
- async function editSettings(ctx: ExtensionCommandContext, options: StatuslineCommandOptions) {
578
- if (ctx.mode !== "tui") {
579
- if (ctx.hasUI) ctx.ui.notify(`Edit settings manually: ${options.settingsPath}`, "info");
580
- return;
581
- }
582
- const current = options.getLoaded();
583
- const edited = await ctx.ui.editor(
584
- "pi-statusline.json — save and close to apply",
585
- current.rawDocument ?? DEFAULT_STATUSLINE_DOCUMENT,
586
- );
587
- if (edited === undefined) return;
588
- let loaded: LoadedStatuslineSettings;
589
- try {
590
- loaded = (options.save ?? saveStatuslineSettingsDocument)(options.settingsPath, edited);
591
- } catch (error) {
592
- ctx.ui.notify(`pi-statusline settings were not saved: ${formatError(error)}`, "error");
593
- return;
594
- }
595
- try {
596
- options.apply(loaded, ctx);
597
- } catch (error) {
598
- const rollbackError = restoreStatuslineSettings(ctx, options, current, loaded);
599
- ctx.ui.notify(
600
- rollbackError
601
- ? `pi-statusline settings could not be applied: ${formatError(error)}; rollback failed: ${formatError(rollbackError)}`
602
- : `pi-statusline settings could not be applied: ${formatError(error)}; previous settings restored.`,
603
- "error",
604
- );
605
- return;
606
- }
607
- const suffix =
608
- loaded.diagnostics.length > 0
609
- ? ` (${loaded.diagnostics.length} warning${loaded.diagnostics.length === 1 ? "" : "s"})`
610
- : "";
611
- ctx.ui.notify(`pi-statusline settings saved and applied${suffix}.`, "info");
612
- }
613
-
614
- function palettePresetDocument(
615
- current: LoadedStatuslineSettings,
616
- palettePreset: PalettePreset,
617
- ): string {
618
- const { parsed } = editableSettings(current, "choosing a palette preset");
619
- if (palettePreset === "custom" && !isRecord(parsed.palette)) {
620
- const seedPreset = isPaletteName(current.config.palettePreset)
621
- ? current.config.palettePreset
622
- : "tokyo-night";
623
- parsed.palette = segmentPaletteForPreset(seedPreset);
624
- } else if (palettePreset !== "custom" && typeof parsed.palette === "string") {
625
- delete parsed.palette;
626
- }
627
- parsed.palettePreset = palettePreset;
628
- return `${JSON.stringify(parsed, null, "\t")}\n`;
629
- }
630
-
631
- function informationProfileDocument(
632
- current: LoadedStatuslineSettings,
633
- profile: InformationProfileName,
634
- ): { nextDocument: string; previousDocument: string } {
635
- const { parsed, rawDocument: previousDocument } = editableSettings(
636
- current,
637
- "changing information level",
638
- );
639
- parsed.segments = [...INFORMATION_PROFILES[profile]];
640
- return {
641
- nextDocument: `${JSON.stringify(parsed, null, "\t")}\n`,
642
- previousDocument,
643
- };
644
- }
645
-
646
- function visibleSegmentNames(current: LoadedStatuslineSettings): SegmentName[] {
647
- return current.config.segments.filter(
648
- (segment): segment is SegmentName => segment !== LINE_BREAK_SEGMENT_NAME,
649
- );
650
- }
651
-
652
- function segmentMenuOrder(current: LoadedStatuslineSettings): SegmentName[] {
653
- const visible = visibleSegmentNames(current);
654
- const visibleSet = new Set(visible);
655
- return [...visible, ...SEGMENT_NAMES.filter((name) => !visibleSet.has(name))];
656
- }
657
-
658
- function hasLineBreakAfter(segments: readonly ConfigSegmentName[], name: SegmentName): boolean {
659
- const index = segments.indexOf(name);
660
- return index >= 0 && segments[index + 1] === LINE_BREAK_SEGMENT_NAME;
661
- }
662
-
663
- function segmentPlacements(
664
- segments: readonly ConfigSegmentName[],
665
- ): Map<SegmentName, { order: number; row: number }> {
666
- const placements = new Map<SegmentName, { order: number; row: number }>();
667
- let order = 0;
668
- let row = 1;
669
- for (const segment of segments) {
670
- if (segment === LINE_BREAK_SEGMENT_NAME) {
671
- row += 1;
672
- continue;
673
- }
674
- placements.set(segment, { order: ++order, row });
675
- }
676
- return placements;
677
- }
678
-
679
- function segmentControlHints(
680
- width: number,
681
- moveMode: boolean,
682
- selected: SegmentName | undefined,
683
- ): string[] {
684
- if (moveMode) {
685
- return width < 30
686
- ? [
687
- `Move mode: ${selected ?? "segment"}`,
688
- "↑↓ move segment",
689
- "Enter/Space finish",
690
- "Esc leave move mode",
691
- ]
692
- : [
693
- `Move mode — ${selected ?? "segment"}`,
694
- "↑↓ move · Enter/Space finish · Esc leave move mode",
695
- ];
696
- }
697
- return width < 30
698
- ? [
699
- "↑↓ navigate",
700
- "Enter/Space toggle",
701
- "M move · B line break",
702
- "Alt+↑/↓ quick move",
703
- "Esc close",
704
- ]
705
- : [
706
- "↑↓ navigate · Enter/Space show/hide · M move mode",
707
- "B add/remove line break after · Alt+↑/↓ quick move · Esc close",
708
- ];
709
- }
710
-
711
- function segmentsDocument(
712
- current: LoadedStatuslineSettings,
713
- name: SegmentName,
714
- shouldShow: boolean,
715
- ): { nextDocument: string; previousDocument: string } {
716
- const { parsed, rawDocument: previousDocument } = editableSettings(current, "changing segments");
717
- const segments = shouldShow
718
- ? [...current.config.segments, ...(current.config.segments.includes(name) ? [] : [name])]
719
- : current.config.segments.filter((segment) => segment !== name);
720
- parsed.segments = normalizeLineBreaks(segments);
721
- return {
722
- nextDocument: `${JSON.stringify(parsed, null, "\t")}\n`,
723
- previousDocument,
724
- };
725
- }
726
-
727
- function lineBreakAfterDocument(
728
- current: LoadedStatuslineSettings,
729
- name: SegmentName,
730
- ): { nextDocument: string; previousDocument: string } {
731
- const { parsed, rawDocument: previousDocument } = editableSettings(
732
- current,
733
- "changing line breaks",
734
- );
735
- const segments = [...current.config.segments];
736
- const segmentIndex = segments.indexOf(name);
737
- if (segments[segmentIndex + 1] === LINE_BREAK_SEGMENT_NAME) {
738
- segments.splice(segmentIndex + 1, 1);
739
- } else {
740
- segments.splice(segmentIndex + 1, 0, LINE_BREAK_SEGMENT_NAME);
741
- }
742
- parsed.segments = segments;
743
- return {
744
- nextDocument: `${JSON.stringify(parsed, null, "\t")}\n`,
745
- previousDocument,
746
- };
747
- }
748
-
749
- function reorderedSegmentsDocument(
750
- current: LoadedStatuslineSettings,
751
- name: SegmentName,
752
- direction: -1 | 1,
753
- ): { nextDocument: string; previousDocument: string } | undefined {
754
- const dataIndexes = current.config.segments.flatMap((segment, index) =>
755
- segment === LINE_BREAK_SEGMENT_NAME ? [] : [index],
756
- );
757
- const currentDataIndex = dataIndexes.findIndex(
758
- (index) => current.config.segments[index] === name,
759
- );
760
- const targetDataIndex = currentDataIndex + direction;
761
- if (currentDataIndex < 0 || targetDataIndex < 0 || targetDataIndex >= dataIndexes.length) {
762
- return undefined;
763
- }
764
- const { parsed, rawDocument: previousDocument } = editableSettings(
765
- current,
766
- "reordering segments",
767
- );
768
- const segments = [...current.config.segments];
769
- const currentIndex = dataIndexes[currentDataIndex];
770
- const targetIndex = dataIndexes[targetDataIndex];
771
- if (currentIndex === undefined || targetIndex === undefined) return undefined;
772
- [segments[currentIndex], segments[targetIndex]] = [segments[targetIndex], segments[currentIndex]];
773
- parsed.segments = segments;
774
- return {
775
- nextDocument: `${JSON.stringify(parsed, null, "\t")}\n`,
776
- previousDocument,
777
- };
778
- }
779
-
780
- function applySegmentsDocumentChange(
781
- change: { nextDocument: string; previousDocument: string },
782
- ctx: ExtensionCommandContext,
783
- options: StatuslineCommandOptions,
784
- ): LoadedStatuslineSettings {
785
- const previous = options.getLoaded();
786
- const save = options.save ?? saveStatuslineSettingsDocument;
787
- const next = save(options.settingsPath, change.nextDocument);
788
- try {
789
- options.apply(next, ctx);
790
- } catch (applyError) {
791
- const rollbackError = restoreStatuslineSettings(ctx, options, previous, next);
792
- if (rollbackError) {
793
- throw new Error(
794
- `runtime update failed: ${formatError(applyError)}; rollback failed: ${formatError(rollbackError)}`,
795
- );
796
- }
797
- throw applyError;
798
- }
799
- return next;
800
- }
801
-
802
- function restoreStatuslineSettings(
803
- ctx: ExtensionCommandContext,
804
- options: StatuslineCommandOptions,
805
- previous: LoadedStatuslineSettings,
806
- saved: LoadedStatuslineSettings,
807
- ): unknown {
808
- try {
809
- if (saved.rawDocument === undefined || saved.fileIdentity === undefined) {
810
- throw new Error("The saved settings document identity is unavailable");
811
- }
812
- removeStatuslineSettingsDocumentIfMatches(
813
- options.settingsPath,
814
- saved.rawDocument,
815
- saved.fileIdentity,
816
- );
817
- if (previous.rawDocument === undefined || previous.settingsPath !== options.settingsPath) {
818
- options.apply(previous, ctx);
819
- return undefined;
820
- }
821
- const restored = (options.save ?? saveStatuslineSettingsDocument)(
822
- options.settingsPath,
823
- previous.rawDocument,
824
- );
825
- options.apply(restored, ctx);
826
- return undefined;
827
- } catch (error) {
828
- return error;
829
- }
830
- }
831
-
832
- function normalizeLineBreaks(segments: readonly ConfigSegmentName[]): ConfigSegmentName[] {
833
- const normalized: ConfigSegmentName[] = [];
834
- for (const segment of segments) {
835
- if (
836
- segment === LINE_BREAK_SEGMENT_NAME &&
837
- (normalized.length === 0 || normalized.at(-1) === LINE_BREAK_SEGMENT_NAME)
838
- ) {
839
- continue;
840
- }
841
- normalized.push(segment);
842
- }
843
- if (normalized.at(-1) === LINE_BREAK_SEGMENT_NAME) normalized.pop();
844
- return normalized;
845
- }
846
-
847
- function editableSettings(
848
- current: LoadedStatuslineSettings,
849
- action: string,
850
- ): { parsed: Record<string, unknown>; rawDocument: string } {
851
- const rawDocument =
852
- current.source === "user" && current.rawDocument !== undefined
853
- ? current.rawDocument
854
- : current.source === "built-in" &&
855
- current.rawDocument === undefined &&
856
- current.diagnostics.length === 0
857
- ? DEFAULT_STATUSLINE_DOCUMENT
858
- : undefined;
859
- if (rawDocument === undefined || current.diagnostics.some((item) => item.code !== "unknown")) {
860
- throw new Error(`Fix pi-statusline.json before ${action}`);
861
- }
862
- const parsed = JSON.parse(rawDocument) as unknown;
863
- if (!isRecord(parsed)) throw new Error("Settings must contain a JSON object");
864
- return { parsed, rawDocument };
865
- }
866
-
867
- function showStatus(ctx: ExtensionCommandContext, options: StatuslineCommandOptions) {
868
- if (!canNotify(ctx)) return;
869
- const loaded = options.getLoaded();
870
- const diagnostics = loaded.diagnostics
871
- .slice(0, 5)
872
- .map((item) => `${item.path || "root"}: ${item.message}`)
873
- .join("; ");
874
- ctx.ui.notify(
875
- [
876
- `pi-statusline source: ${loaded.source}`,
877
- `active path: ${loaded.settingsPath}`,
878
- `save target: ${options.settingsPath}`,
879
- `palette preset: ${loaded.config.palettePreset}`,
880
- `density: ${loaded.config.density}`,
881
- `separator: ${loaded.config.separator}`,
882
- `information: ${inferInformationProfile(loaded.config.segments)}`,
883
- `segments: ${loaded.config.segments.join(", ") || "none"}`,
884
- diagnostics ? `warnings: ${diagnostics}` : "warnings: none",
885
- ].join("\n"),
886
- loaded.diagnostics.length > 0 ? "warning" : "info",
887
- );
888
- }
889
-
890
- function showHelp(ctx: ExtensionCommandContext, settingsPath: string) {
891
- if (!canNotify(ctx)) return;
892
- ctx.ui.notify(
893
- [
894
- "/statusline — open Appearance, Information, Advanced, Status, and Help",
895
- "/statusline settings — edit and apply JSON",
896
- "/statusline status — show source, path, information level, and warnings",
897
- "/statusline help — show this help",
898
- "Menu actions: Appearance, Information, Advanced, Status, Help.",
899
- "Information levels: minimal, balanced, detailed; any other segment array is custom.",
900
- "Advanced actions: Custom layout, Edit settings JSON, Back.",
901
- `Settings: ${settingsPath}`,
902
- "Fields: palettePreset, palette, density, separator, segments, segmentText, extensionStatusIcons",
903
- "Named presets ignore but preserve palette; custom uses its per-segment fg/bg colors.",
904
- "Responsive rows retain context, model, location, and active work before decorative data.",
905
- "Custom layout can show, hide, reorder, or split data segments across rows.",
906
- "Press M for move mode, Alt+Up/Alt+Down for quick move, and B for a line break.",
907
- "Line breaks (line_break) may repeat when separated by data segments, but cannot be consecutive.",
908
- "segmentText supports prefix and suffix strings around Pi-owned dynamic values.",
909
- "segmentText.model also supports truncationLength, truncationSymbol, and truncationDirection (start, middle, end).",
910
- ].join("\n"),
911
- "info",
912
- );
913
- }
914
-
915
- function isRecord(value: unknown): value is Record<string, unknown> {
916
- return typeof value === "object" && value !== null && !Array.isArray(value);
917
- }
918
-
919
- function isPaletteName(value: PalettePreset): value is PaletteName {
920
- return (PALETTE_NAMES as readonly PalettePreset[]).includes(value);
921
- }
922
-
923
- function canNotify(ctx: ExtensionCommandContext): boolean {
924
- return ctx.mode === "tui" || ctx.hasUI;
925
- }
926
-
927
- function formatError(error: unknown): string {
928
- return error instanceof Error ? error.message : String(error);
929
- }