@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
package/src/config.ts ADDED
@@ -0,0 +1,307 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
4
+ import { Context, Effect, Layer, Schema } from "effect";
5
+ import * as FileSystem from "effect/FileSystem";
6
+ import * as PlatformError from "effect/PlatformError";
7
+ export type { IconMode } from "./icons.ts";
8
+
9
+ export type SettingsLanguage = "en";
10
+
11
+ const CONFIG_FILE_NAME = "tui.json";
12
+
13
+ const IconModeSchema = Schema.Literals(["auto", "nerd", "ascii"] as const);
14
+ const SettingsLanguageSchema = Schema.Literals(["en"] as const);
15
+
16
+ export class TuiConfig extends Schema.Class<TuiConfig>("tui/config/TuiConfig")({
17
+ enabled: Schema.Boolean,
18
+ settingsLanguage: SettingsLanguageSchema,
19
+ vim: Schema.Boolean,
20
+ icons: Schema.Struct({ mode: IconModeSchema }),
21
+ footerSegments: Schema.Struct({
22
+ cwd: Schema.Boolean,
23
+ gitBranch: Schema.Boolean,
24
+ gitStatus: Schema.Boolean,
25
+ gitCommit: Schema.Boolean,
26
+ runtime: Schema.Boolean,
27
+ context: Schema.Boolean,
28
+ tokens: Schema.Boolean,
29
+ cost: Schema.Boolean,
30
+ extensionStatuses: Schema.Boolean,
31
+ }),
32
+ telemetry: Schema.Struct({
33
+ enabled: Schema.Boolean,
34
+ tps: Schema.Boolean,
35
+ ttft: Schema.Boolean,
36
+ duration: Schema.Boolean,
37
+ tokens: Schema.Boolean,
38
+ stalls: Schema.Boolean,
39
+ cost: Schema.Boolean,
40
+ }),
41
+ }) {}
42
+
43
+ export type TelemetryConfig = TuiConfig["telemetry"];
44
+
45
+ export const DEFAULT_CONFIG: TuiConfig = {
46
+ enabled: true,
47
+ settingsLanguage: "en",
48
+ vim: false,
49
+ icons: { mode: "auto" },
50
+ footerSegments: {
51
+ cwd: true,
52
+ gitBranch: true,
53
+ gitStatus: true,
54
+ gitCommit: false,
55
+ runtime: true,
56
+ context: true,
57
+ tokens: true,
58
+ cost: true,
59
+ extensionStatuses: true,
60
+ },
61
+ telemetry: {
62
+ enabled: true,
63
+ tps: true,
64
+ ttft: true,
65
+ duration: true,
66
+ tokens: true,
67
+ stalls: true,
68
+ cost: true,
69
+ },
70
+ };
71
+
72
+ export function getConfigPath(): string {
73
+ return join(getAgentDir(), CONFIG_FILE_NAME);
74
+ }
75
+
76
+ // On-disk format is a partial config: every field may be absent, but any
77
+ // present field must have the correct type. Extra keys are ignored so the
78
+ // file stays forward-compatible.
79
+ const OptionalBoolean = Schema.optional(Schema.Boolean);
80
+ const OptionalIconMode = Schema.optional(IconModeSchema);
81
+ const OptionalSettingsLanguage = Schema.optional(SettingsLanguageSchema);
82
+
83
+ const FileSchema = Schema.fromJsonString(
84
+ Schema.Struct({
85
+ enabled: OptionalBoolean,
86
+ settingsLanguage: OptionalSettingsLanguage,
87
+ vim: OptionalBoolean,
88
+ icons: Schema.optional(Schema.Struct({ mode: OptionalIconMode })),
89
+ footerSegments: Schema.optional(
90
+ Schema.Struct({
91
+ cwd: OptionalBoolean,
92
+ gitBranch: OptionalBoolean,
93
+ gitStatus: OptionalBoolean,
94
+ gitCommit: OptionalBoolean,
95
+ runtime: OptionalBoolean,
96
+ context: OptionalBoolean,
97
+ tokens: OptionalBoolean,
98
+ cost: OptionalBoolean,
99
+ extensionStatuses: OptionalBoolean,
100
+ }),
101
+ ),
102
+ telemetry: Schema.optional(
103
+ Schema.Struct({
104
+ enabled: OptionalBoolean,
105
+ tps: OptionalBoolean,
106
+ ttft: OptionalBoolean,
107
+ duration: OptionalBoolean,
108
+ tokens: OptionalBoolean,
109
+ stalls: OptionalBoolean,
110
+ cost: OptionalBoolean,
111
+ }),
112
+ ),
113
+ }),
114
+ { space: 2 },
115
+ );
116
+
117
+ type TuiConfigFile = typeof FileSchema.Type;
118
+
119
+ export const encodeConfig = Schema.encodeSync(FileSchema);
120
+ export const decodeConfig = Schema.decodeSync(FileSchema);
121
+
122
+ export const decodeConfigEffect = Schema.decodeEffect(FileSchema);
123
+
124
+ export function applyDefaults(partial: TuiConfigFile): TuiConfig {
125
+ return {
126
+ enabled: partial.enabled ?? DEFAULT_CONFIG.enabled,
127
+ settingsLanguage: partial.settingsLanguage ?? DEFAULT_CONFIG.settingsLanguage,
128
+ vim: partial.vim ?? DEFAULT_CONFIG.vim,
129
+ icons: {
130
+ mode: partial.icons?.mode ?? DEFAULT_CONFIG.icons.mode,
131
+ },
132
+ footerSegments: {
133
+ cwd: partial.footerSegments?.cwd ?? DEFAULT_CONFIG.footerSegments.cwd,
134
+ gitBranch: partial.footerSegments?.gitBranch ?? DEFAULT_CONFIG.footerSegments.gitBranch,
135
+ gitStatus: partial.footerSegments?.gitStatus ?? DEFAULT_CONFIG.footerSegments.gitStatus,
136
+ gitCommit: partial.footerSegments?.gitCommit ?? DEFAULT_CONFIG.footerSegments.gitCommit,
137
+ runtime: partial.footerSegments?.runtime ?? DEFAULT_CONFIG.footerSegments.runtime,
138
+ context: partial.footerSegments?.context ?? DEFAULT_CONFIG.footerSegments.context,
139
+ tokens: partial.footerSegments?.tokens ?? DEFAULT_CONFIG.footerSegments.tokens,
140
+ cost: partial.footerSegments?.cost ?? DEFAULT_CONFIG.footerSegments.cost,
141
+ extensionStatuses:
142
+ partial.footerSegments?.extensionStatuses ??
143
+ DEFAULT_CONFIG.footerSegments.extensionStatuses,
144
+ },
145
+ telemetry: {
146
+ enabled: partial.telemetry?.enabled ?? DEFAULT_CONFIG.telemetry.enabled,
147
+ tps: partial.telemetry?.tps ?? DEFAULT_CONFIG.telemetry.tps,
148
+ ttft: partial.telemetry?.ttft ?? DEFAULT_CONFIG.telemetry.ttft,
149
+ duration: partial.telemetry?.duration ?? DEFAULT_CONFIG.telemetry.duration,
150
+ tokens: partial.telemetry?.tokens ?? DEFAULT_CONFIG.telemetry.tokens,
151
+ stalls: partial.telemetry?.stalls ?? DEFAULT_CONFIG.telemetry.stalls,
152
+ cost: partial.telemetry?.cost ?? DEFAULT_CONFIG.telemetry.cost,
153
+ },
154
+ };
155
+ }
156
+
157
+ export class ConfigReadError extends Schema.TaggedError<ConfigReadError>()("ConfigReadError", {
158
+ path: Schema.String,
159
+ message: Schema.String,
160
+ }) {}
161
+
162
+ export class ConfigParseError extends Schema.TaggedError<ConfigParseError>()("ConfigParseError", {
163
+ path: Schema.String,
164
+ message: Schema.String,
165
+ }) {}
166
+
167
+ export class ConfigWriteError extends Schema.TaggedError<ConfigWriteError>()("ConfigWriteError", {
168
+ path: Schema.String,
169
+ message: Schema.String,
170
+ }) {}
171
+
172
+ export type ConfigError = ConfigReadError | ConfigParseError | ConfigWriteError;
173
+
174
+ export class TuiConfigService extends Context.Service<
175
+ TuiConfigService,
176
+ {
177
+ readonly path: string;
178
+ readonly load: Effect.Effect<TuiConfig, ConfigError, never>;
179
+ readonly loadOrDefault: Effect.Effect<TuiConfig, never, never>;
180
+ readonly save: (config: TuiConfig) => Effect.Effect<void, ConfigWriteError>;
181
+ }
182
+ >()("tui/config/TuiConfigService") {
183
+ static make(path: string): Layer.Layer<TuiConfigService, never, FileSystem.FileSystem> {
184
+ return Layer.effect(
185
+ TuiConfigService,
186
+ Effect.gen(function* () {
187
+ const fs = yield* FileSystem.FileSystem;
188
+
189
+ const load = Effect.gen(function* () {
190
+ const exists = yield* fs
191
+ .exists(path)
192
+ .pipe(
193
+ Effect.catch(
194
+ (err: PlatformError.PlatformError) =>
195
+ new ConfigReadError({ path, message: err.message }),
196
+ ),
197
+ );
198
+
199
+ if (!exists) {
200
+ yield* fs.makeDirectory(dirname(path), { recursive: true }).pipe(
201
+ Effect.andThen(() => fs.writeFileString(path, encodeConfig(DEFAULT_CONFIG) + "\n")),
202
+ Effect.catch(
203
+ (err: PlatformError.PlatformError) =>
204
+ new ConfigWriteError({ path, message: err.message }),
205
+ ),
206
+ );
207
+ return applyDefaults({});
208
+ }
209
+
210
+ const config = yield* fs.readFileString(path).pipe(
211
+ Effect.flatMap(decodeConfigEffect),
212
+ Effect.catchTags({
213
+ SchemaError: (err) => new ConfigParseError({ path, message: err.message }),
214
+ PlatformError: (err) => new ConfigReadError({ path, message: err.message }),
215
+ }),
216
+ );
217
+
218
+ return applyDefaults(config);
219
+ });
220
+
221
+ const loadOrDefault = load.pipe(
222
+ Effect.catch((err: ConfigError) =>
223
+ Effect.gen(function* () {
224
+ yield* Effect.logWarning(`TUI config load failed: ${err.message}`);
225
+ return applyDefaults({});
226
+ }),
227
+ ),
228
+ );
229
+
230
+ const save = Effect.fn("save")(function* (config: TuiConfig) {
231
+ yield* fs
232
+ .makeDirectory(dirname(path), { recursive: true })
233
+ .pipe(
234
+ Effect.catch(
235
+ (err: PlatformError.PlatformError) =>
236
+ new ConfigWriteError({ path, message: err.message }),
237
+ ),
238
+ );
239
+ yield* fs
240
+ .writeFileString(path, JSON.stringify(config, null, 2) + "\n")
241
+ .pipe(
242
+ Effect.catch(
243
+ (err: PlatformError.PlatformError) =>
244
+ new ConfigWriteError({ path, message: err.message }),
245
+ ),
246
+ );
247
+ });
248
+
249
+ return TuiConfigService.of({ path, load, loadOrDefault, save });
250
+ }),
251
+ );
252
+ }
253
+
254
+ static readonly layer: Layer.Layer<TuiConfigService, never, FileSystem.FileSystem> =
255
+ TuiConfigService.make(getConfigPath());
256
+
257
+ static readonly layerTest = (
258
+ path: string,
259
+ fileSystem: Partial<FileSystem.FileSystem>,
260
+ ): Layer.Layer<TuiConfigService> =>
261
+ TuiConfigService.make(path).pipe(Layer.provide(FileSystem.layerNoop(fileSystem)));
262
+ }
263
+
264
+ // // ------------------------------------------------------------------
265
+ // // Temporary imperative wrappers for backwards compatibility.
266
+ // // TODO: remove these once src/index.ts is wired to TuiConfigService.
267
+ // // ------------------------------------------------------------------
268
+ //
269
+ // export function ensureConfigExists(): void {
270
+ // const path = getConfigPath();
271
+ // if (existsSync(path)) return;
272
+ // try {
273
+ // const agentDir = getAgentDir();
274
+ // if (!existsSync(agentDir)) mkdirSync(agentDir, { recursive: true });
275
+ // writeFileSync(path, JSON.stringify(DEFAULT_CONFIG, null, 2) + "\n", "utf8");
276
+ // } catch {}
277
+ // }
278
+ //
279
+ // export function loadConfig(notify?: (msg: string, level: "warning" | "info") => void): TuiConfig {
280
+ // const path = getConfigPath();
281
+ // if (!existsSync(path)) {
282
+ // ensureConfigExists();
283
+ // return applyDefaults({});
284
+ // }
285
+ //
286
+ // try {
287
+ // const raw = readFileSync(path, "utf8");
288
+ // const parsed: unknown = JSON.parse(raw);
289
+ // const partial = Schema.decodeUnknownSync(FileSchema, { onExcessProperty: "ignore" })(parsed);
290
+ // return applyDefaults(partial);
291
+ // } catch (err) {
292
+ // notify?.(
293
+ // `tui config parse error: ${err instanceof Error ? err.message : String(err)}`,
294
+ // "warning",
295
+ // );
296
+ // return applyDefaults({});
297
+ // }
298
+ // }
299
+ //
300
+ // export function saveConfig(config: TuiConfig): void {
301
+ // const path = getConfigPath();
302
+ // try {
303
+ // const agentDir = getAgentDir();
304
+ // if (!existsSync(agentDir)) mkdirSync(agentDir, { recursive: true });
305
+ // writeFileSync(path, JSON.stringify(config, null, 2) + "\n", "utf8");
306
+ // } catch {}
307
+ // }
@@ -0,0 +1,44 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { buildBoxFrame, composeBorderLine } from "./box-frame.ts";
3
+
4
+ const compose = (
5
+ frame: NonNullable<ReturnType<typeof buildBoxFrame>>,
6
+ kind: "top" | "bottom" = "top",
7
+ ) => composeBorderLine(frame, kind);
8
+
9
+ it("defaults to the decorative ───── tail", () => {
10
+ const frame = buildBoxFrame(20, { label: "hi", labelWidth: 2 })!;
11
+ assert.strictEqual(frame.top.labelPrefix, "─── ");
12
+ assert.strictEqual(frame.top.labelSuffix, " ─────");
13
+ // 4 (─── ) + 2 (label) + 6 ( ─────) = 12 fixed; 18 - 12 = 6 fill dashes.
14
+ assert.strictEqual(compose(frame), `╭─── hi ${"─".repeat(11)}╮`);
15
+ });
16
+
17
+ it("honors a custom label suffix", () => {
18
+ const frame = buildBoxFrame(20, { label: "↓ 5 more", labelWidth: 8, labelSuffix: " " })!;
19
+ assert.strictEqual(frame.top.labelPrefix, "─── ");
20
+ assert.strictEqual(frame.top.labelSuffix, " ");
21
+ // 4 + 8 + 1 = 13 fixed; 18 - 13 = 5 fill dashes.
22
+ assert.strictEqual(compose(frame), `╭─── ↓ 5 more ${"─".repeat(5)}╮`);
23
+ });
24
+
25
+ it("clips to a plain frame when the label plus a custom suffix would overflow", () => {
26
+ // 4 (─── ) + 8 (label) + 1 (suffix) = 13 > width - 2 = 10 → label dropped.
27
+ const frame = buildBoxFrame(12, { label: "↓ 5 more", labelWidth: 8, labelSuffix: " " });
28
+ assert.strictEqual(frame!.top.label, null);
29
+ assert.strictEqual(`${frame!.top.left}${frame!.top.fill}${frame!.top.right}`, "╭──────────╮");
30
+ });
31
+
32
+ it("leaves the bottom border untouched by the label options", () => {
33
+ const frame = buildBoxFrame(20, { label: "hi", labelWidth: 2, labelSuffix: " " })!;
34
+ assert.strictEqual(frame.bottom.left, "╰");
35
+ assert.strictEqual(frame.bottom.right, "╯");
36
+ assert.strictEqual(frame.bottom.fill, "─".repeat(18));
37
+ });
38
+
39
+ it("paints the chrome but passes the label through raw", () => {
40
+ const frame = buildBoxFrame(20, { label: "hi", labelWidth: 2 })!;
41
+ const paint = (text: string) => `<${text}>`;
42
+ assert.strictEqual(composeBorderLine(frame, "top", paint), `<╭><─── >hi< ─────><──────><╮>`);
43
+ assert.strictEqual(composeBorderLine(frame, "bottom", paint), `<╰><──────────────────><╯>`);
44
+ });
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Pure box-frame model for the house rounded border (╭─╮│╰─╯).
3
+ *
4
+ * This module is deliberately free of pi imports (`@earendil-works/*`,
5
+ * `effect`) so pi-free cores — the inquiry scene model in particular — can
6
+ * build the same frame without dragging in a terminal runtime. `BorderedBox`
7
+ * is the themed component wrapper around it: it paints the segments with the
8
+ * Theme, applies an optional per-line background, and caches.
9
+ */
10
+
11
+ export interface BoxFrameOptions {
12
+ /**
13
+ * Text embedded in the top border (`╭─── label ─────╮`). May be pre-themed
14
+ * (ANSI); pass `labelWidth` so the fill accounts for it. Omitted when the
15
+ * box is too narrow to fit `─── label ─────` without overflowing.
16
+ */
17
+ readonly label?: string;
18
+ /**
19
+ * Visible width of the label in terminal columns. Measured by the caller
20
+ * (ANSI-aware renderers pass their own width function; pi-free cores pass
21
+ * theirs). Defaults to the code-point length of the SGR-stripped label.
22
+ */
23
+ readonly labelWidth?: number;
24
+ /** Horizontal padding between the rails and the content. Defaults to 1. */
25
+ readonly paddingX?: number;
26
+ /** Width below which the label is never attempted. Defaults to 8. */
27
+ readonly minLabelWidth?: number;
28
+ /**
29
+ * Decorative dash run after the label (` ─────`). Overridable so callers
30
+ * with a different tail (e.g. a scroll-hint that trails with a single
31
+ * space) can reuse the same layout arithmetic. Defaults to " ─────".
32
+ */
33
+ readonly labelSuffix?: string;
34
+ }
35
+
36
+ /** One border line split into the three segments a renderer styles together. */
37
+ export interface BoxBorderLine {
38
+ readonly left: string;
39
+ readonly fill: string;
40
+ readonly right: string;
41
+ }
42
+
43
+ /** Top border, additionally carrying the label and its decorative dashes. */
44
+ export interface BoxTopBorder extends BoxBorderLine {
45
+ /** The embedded label text (as passed); null when absent or too narrow. */
46
+ readonly label: string | null;
47
+ /** The `─── ` run before the label; null when the label is omitted. */
48
+ readonly labelPrefix: string | null;
49
+ /** The ` ─────` run after the label; null when the label is omitted. */
50
+ readonly labelSuffix: string | null;
51
+ }
52
+
53
+ /**
54
+ * The computed frame: ready-to-compose segments plus the geometry a body
55
+ * needs (content width and per-side rails/padding). All strings are raw
56
+ * border characters — no ANSI, no styling.
57
+ */
58
+ export interface BoxFrame {
59
+ readonly top: BoxTopBorder;
60
+ readonly bottom: BoxBorderLine;
61
+ readonly railLeft: string;
62
+ readonly railRight: string;
63
+ readonly padLeft: string;
64
+ readonly padRight: string;
65
+ readonly contentWidth: number;
66
+ }
67
+
68
+ const LABEL_PREFIX = "─── ";
69
+ const LABEL_SUFFIX = " ─────";
70
+
71
+ /**
72
+ * Build the frame segments for a box of the given width, or null when the
73
+ * width is too small to hold a border at all (≤ 2 columns).
74
+ */
75
+ export const buildBoxFrame = (width: number, options: BoxFrameOptions = {}): BoxFrame | null => {
76
+ if (width <= 2) return null;
77
+ const paddingX = options.paddingX ?? 1;
78
+ const contentWidth = Math.max(1, width - 2 - paddingX * 2);
79
+ const pad = " ".repeat(Math.max(0, paddingX));
80
+ const fill = "─".repeat(width - 2);
81
+ const plain: BoxTopBorder = {
82
+ left: "╭",
83
+ fill,
84
+ right: "╮",
85
+ label: null,
86
+ labelPrefix: null,
87
+ labelSuffix: null,
88
+ };
89
+ const bottom: BoxBorderLine = { left: "╰", fill, right: "╯" };
90
+ const base = {
91
+ bottom,
92
+ railLeft: "│",
93
+ railRight: "│",
94
+ padLeft: pad,
95
+ padRight: pad,
96
+ contentWidth,
97
+ };
98
+
99
+ const label = options.label;
100
+ const minLabelWidth = options.minLabelWidth ?? 8;
101
+ if (label === undefined || width < minLabelWidth) {
102
+ return { top: plain, ...base };
103
+ }
104
+ const labelWidth = options.labelWidth ?? sgrFreeCodePointLength(stripSgr(label));
105
+ const labelSuffix = options.labelSuffix ?? LABEL_SUFFIX;
106
+ // Fixed chrome: corners + the decorative dash runs around the label.
107
+ const fixed = LABEL_PREFIX.length + labelWidth + labelSuffix.length;
108
+ if (fixed > width - 2) {
109
+ // The label would overflow the top border; render a plain frame instead.
110
+ return { top: plain, ...base };
111
+ }
112
+ return {
113
+ top: {
114
+ left: "╭",
115
+ fill: "─".repeat(width - 2 - fixed),
116
+ right: "╮",
117
+ label,
118
+ labelPrefix: LABEL_PREFIX,
119
+ labelSuffix,
120
+ },
121
+ ...base,
122
+ };
123
+ };
124
+
125
+ /**
126
+ * Compose one finished border line from a frame, applying `paint` to the
127
+ * chrome (corners, decorative dash runs, fill) and passing the embedded
128
+ * label through raw. Themed wrappers use this to keep the label un-painted
129
+ * (they pre-style it); pi-free renderers can inject their own text styling
130
+ * or pass the identity function.
131
+ */
132
+ export const composeBorderLine = (
133
+ frame: BoxFrame,
134
+ kind: "top" | "bottom",
135
+ paint: (text: string) => string = (text) => text,
136
+ ): string => {
137
+ if (kind === "bottom") {
138
+ return paint(frame.bottom.left) + paint(frame.bottom.fill) + paint(frame.bottom.right);
139
+ }
140
+ const top = frame.top;
141
+ return (
142
+ paint(top.left) +
143
+ paint(top.labelPrefix ?? "") +
144
+ (top.label ?? "") +
145
+ paint(top.labelSuffix ?? "") +
146
+ paint(top.fill) +
147
+ paint(top.right)
148
+ );
149
+ };
150
+
151
+ /** Strip SGR (color/style) escape sequences only — cosmetic, not styling. */
152
+ const stripSgr = (text: string): string =>
153
+ text.replace(new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "g"), "");
154
+
155
+ /**
156
+ * Fallback label measurement: code points of the SGR-stripped text. Accurate
157
+ * for ASCII and most labels; callers with wide/emoji or tab-heavy labels pass
158
+ * `labelWidth` explicitly.
159
+ */
160
+ const sgrFreeCodePointLength = (text: string): number => Array.from(text).length;