@restranger/repi-lib 0.0.0-stage → 0.0.1-44677f3
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/README.md +90 -2
- package/package.json +26 -5
- package/src/completion.ts +61 -0
- package/src/config.ts +110 -0
- package/src/contracts/advisor.ts +20 -0
- package/src/contracts/index.ts +5 -0
- package/src/contracts/modes.ts +31 -0
- package/src/contracts/permissions.ts +225 -0
- package/src/contracts/subagents.ts +18 -0
- package/src/contracts/ui.ts +25 -0
- package/src/contracts.ts +39 -0
- package/src/disposable.ts +29 -0
- package/src/index.ts +11 -0
- package/src/model-scoring.ts +118 -0
- package/src/pi.ts +285 -0
- package/src/seam.ts +205 -0
- package/src/session.ts +28 -0
- package/src/shimmer.ts +275 -0
- package/src/text.ts +344 -0
package/src/shimmer.ts
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import type { PiUiCustomTheme } from "./pi.js";
|
|
2
|
+
|
|
3
|
+
/** Stock default working label (`defaultWorkingMessage`). */
|
|
4
|
+
export const WORKING_LABEL = "Working";
|
|
5
|
+
|
|
6
|
+
/** Matches the stock spinner cadence (`Loader.DEFAULT_INTERVAL_MS`). */
|
|
7
|
+
export const SHIMMER_INTERVAL_MS = 80;
|
|
8
|
+
|
|
9
|
+
/** Characters covered by the highlight window. */
|
|
10
|
+
export const HIGHLIGHT_WIDTH = 3;
|
|
11
|
+
|
|
12
|
+
export const DEFAULT_COMPACTION_LABEL = "Compacting context...";
|
|
13
|
+
|
|
14
|
+
export const WORKING_LABEL_LENGTH = Array.from(WORKING_LABEL).length;
|
|
15
|
+
|
|
16
|
+
export interface StatusIndicatorLike {
|
|
17
|
+
kind?: string;
|
|
18
|
+
message?: string;
|
|
19
|
+
setMessage?(message: string): void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface ParsedCompactionLabel {
|
|
23
|
+
readonly baseLabel: string;
|
|
24
|
+
readonly cancelHint: string | undefined;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function getHighlightWidth(labelLength: number): number {
|
|
28
|
+
return Math.max(1, Math.min(HIGHLIGHT_WIDTH, labelLength));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function getSweepWindow(
|
|
32
|
+
labelLength: number,
|
|
33
|
+
step: number,
|
|
34
|
+
): {
|
|
35
|
+
start: number;
|
|
36
|
+
end: number;
|
|
37
|
+
} {
|
|
38
|
+
const highlightWidth = getHighlightWidth(labelLength);
|
|
39
|
+
const cycleLength = labelLength + highlightWidth;
|
|
40
|
+
const start = (step % cycleLength) - highlightWidth;
|
|
41
|
+
|
|
42
|
+
return {
|
|
43
|
+
start,
|
|
44
|
+
end: start + highlightWidth,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const pad2 = (value: number): string => String(value).padStart(2, "0");
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Elapsed working time as a suffix, one unit pair at a time: `12s`, `1m05s`,
|
|
52
|
+
* `1h00m`, `2d03h`, `3w01d`. Each step carries its remainder down, so a day
|
|
53
|
+
* never shows as `24h00m` and 60 minutes is exactly `1h00m`. Returns
|
|
54
|
+
* `undefined` below one second so the first frames read exactly like the
|
|
55
|
+
* stock label.
|
|
56
|
+
*/
|
|
57
|
+
export function formatElapsedDuration(elapsedMs: number): string | undefined {
|
|
58
|
+
if (!Number.isFinite(elapsedMs) || elapsedMs < 1000) return undefined;
|
|
59
|
+
|
|
60
|
+
let value = Math.floor(elapsedMs / 1000);
|
|
61
|
+
if (value < 60) return `${value}s`;
|
|
62
|
+
|
|
63
|
+
const seconds = value % 60;
|
|
64
|
+
value = Math.floor(value / 60);
|
|
65
|
+
if (value < 60) return `${value}m${pad2(seconds)}s`;
|
|
66
|
+
|
|
67
|
+
const minutes = value % 60;
|
|
68
|
+
value = Math.floor(value / 60);
|
|
69
|
+
if (value < 24) return `${value}h${pad2(minutes)}m`;
|
|
70
|
+
|
|
71
|
+
const hours = value % 24;
|
|
72
|
+
value = Math.floor(value / 24);
|
|
73
|
+
if (value < 7) return `${value}d${pad2(hours)}h`;
|
|
74
|
+
|
|
75
|
+
return `${Math.floor(value / 7)}w${pad2(value % 7)}d`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Renders a label with a highlight window sweeping across it. Only the
|
|
80
|
+
* window is styled: the rest of the label stays unstyled so the color function
|
|
81
|
+
* wrapping the message keeps applying to it.
|
|
82
|
+
*/
|
|
83
|
+
export function renderShimmerLabel(
|
|
84
|
+
theme: PiUiCustomTheme | { bold(text: string): string } | undefined,
|
|
85
|
+
label: string,
|
|
86
|
+
step: number,
|
|
87
|
+
): string {
|
|
88
|
+
const characters = Array.from(label);
|
|
89
|
+
if (characters.length === 0) return "";
|
|
90
|
+
|
|
91
|
+
const { start, end } = getSweepWindow(characters.length, step);
|
|
92
|
+
const from = Math.max(0, start);
|
|
93
|
+
const to = Math.min(characters.length, end);
|
|
94
|
+
if (to <= from) {
|
|
95
|
+
return label;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const before = characters.slice(0, from).join("");
|
|
99
|
+
const highlighted = characters.slice(from, to).join("");
|
|
100
|
+
const after = characters.slice(to).join("");
|
|
101
|
+
|
|
102
|
+
let boldText = "";
|
|
103
|
+
if (theme && typeof (theme as { bold?: unknown }).bold === "function") {
|
|
104
|
+
try {
|
|
105
|
+
const styled = (theme as { bold(t: string): string }).bold(highlighted);
|
|
106
|
+
if (styled !== highlighted) {
|
|
107
|
+
boldText = styled;
|
|
108
|
+
}
|
|
109
|
+
} catch {
|
|
110
|
+
// Ignore theme errors
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (!boldText) {
|
|
114
|
+
boldText = `\x1b[1m${highlighted}\x1b[22m`;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return before + boldText + after;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Stock label plus shimmer window plus elapsed-time suffix. The suffix is
|
|
122
|
+
* parenthesized, mirroring stock's `Working (esc to interrupt)`, and stays
|
|
123
|
+
* unstyled so the color function stock wraps the whole message with keeps
|
|
124
|
+
* applying to it.
|
|
125
|
+
*/
|
|
126
|
+
export function renderWorkingMessage(
|
|
127
|
+
theme: PiUiCustomTheme | { bold(text: string): string } | undefined,
|
|
128
|
+
label: string,
|
|
129
|
+
step: number,
|
|
130
|
+
elapsedMs: number,
|
|
131
|
+
): string {
|
|
132
|
+
const elapsed = formatElapsedDuration(elapsedMs);
|
|
133
|
+
const fullText = elapsed === undefined ? label : `${label} (${elapsed})`;
|
|
134
|
+
|
|
135
|
+
return renderShimmerLabel(theme, fullText, step);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Parses a compaction status message into base label and optional cancel hint suffix.
|
|
140
|
+
* e.g. "Compacting context... (escape to cancel)" -> { baseLabel: "Compacting context...", cancelHint: "(escape to cancel)" }
|
|
141
|
+
*/
|
|
142
|
+
export function parseCompactionMessage(message: string | undefined): ParsedCompactionLabel {
|
|
143
|
+
if (!message) {
|
|
144
|
+
return { baseLabel: DEFAULT_COMPACTION_LABEL, cancelHint: "(escape to cancel)" };
|
|
145
|
+
}
|
|
146
|
+
const match = message.match(/^(.*?)(?:\s+(\([^)]+\)))?$/);
|
|
147
|
+
const baseLabel = match?.[1] ? match[1].trim() : DEFAULT_COMPACTION_LABEL;
|
|
148
|
+
const cancelHint = match?.[2] ? match[2].trim() : undefined;
|
|
149
|
+
return { baseLabel, cancelHint };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Compaction label plus shimmer window plus elapsed-time suffix plus cancel hint.
|
|
154
|
+
*/
|
|
155
|
+
export function renderCompactionMessage(
|
|
156
|
+
theme: PiUiCustomTheme | { bold(text: string): string } | undefined,
|
|
157
|
+
baseLabel: string,
|
|
158
|
+
cancelHint: string | undefined,
|
|
159
|
+
step: number,
|
|
160
|
+
elapsedMs: number,
|
|
161
|
+
): string {
|
|
162
|
+
const elapsed = formatElapsedDuration(elapsedMs);
|
|
163
|
+
let fullText = baseLabel;
|
|
164
|
+
if (elapsed !== undefined) {
|
|
165
|
+
fullText += ` (${elapsed})`;
|
|
166
|
+
}
|
|
167
|
+
if (cancelHint !== undefined) {
|
|
168
|
+
fullText += ` ${cancelHint}`;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return renderShimmerLabel(theme, fullText, step);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function isStatusIndicatorLike(node: unknown): node is StatusIndicatorLike {
|
|
175
|
+
if (!node || typeof node !== "object") return false;
|
|
176
|
+
const record = node as Record<string, unknown>;
|
|
177
|
+
return record.kind === "compaction" && typeof record.setMessage === "function";
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Searches the TUI component tree for an active compaction StatusIndicator.
|
|
182
|
+
* Handles:
|
|
183
|
+
* - Direct StatusIndicator instances
|
|
184
|
+
* - CustomEditor embedded mode (`workingStatusIndicator`)
|
|
185
|
+
* - Rounded/custom editor modes (`embeddedStatusIndicator`, `workingStatusIndicator`)
|
|
186
|
+
* - Generic container properties (`activeStatusIndicator`, `statusIndicator`, etc.)
|
|
187
|
+
* - Generic recursive inspection of children arrays (`children`)
|
|
188
|
+
* - Fullscreen alt-screen layout roots (`layoutRoot`)
|
|
189
|
+
* - Stack entries (`entries[].component`)
|
|
190
|
+
*/
|
|
191
|
+
export function findCompactionIndicator(
|
|
192
|
+
node: unknown,
|
|
193
|
+
depth = 0,
|
|
194
|
+
seen = new Set<unknown>(),
|
|
195
|
+
): StatusIndicatorLike | undefined {
|
|
196
|
+
if (!node || typeof node !== "object" || depth > 8 || seen.has(node)) {
|
|
197
|
+
return undefined;
|
|
198
|
+
}
|
|
199
|
+
seen.add(node);
|
|
200
|
+
|
|
201
|
+
if (isStatusIndicatorLike(node)) {
|
|
202
|
+
return node;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const record = node as Record<string, unknown>;
|
|
206
|
+
|
|
207
|
+
// Check known indicator property names directly first
|
|
208
|
+
const knownFields = ["workingStatusIndicator", "embeddedStatusIndicator", "activeStatusIndicator", "statusIndicator"];
|
|
209
|
+
for (const field of knownFields) {
|
|
210
|
+
try {
|
|
211
|
+
const val = record[field];
|
|
212
|
+
if (isStatusIndicatorLike(val)) return val;
|
|
213
|
+
} catch {
|
|
214
|
+
// Ignore getter errors
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// Check immediate children first to prioritize editor and status containers
|
|
219
|
+
if (Array.isArray(record.children)) {
|
|
220
|
+
for (const child of record.children) {
|
|
221
|
+
if (!child || typeof child !== "object") continue;
|
|
222
|
+
if (isStatusIndicatorLike(child)) return child;
|
|
223
|
+
const childRecord = child as Record<string, unknown>;
|
|
224
|
+
for (const field of knownFields) {
|
|
225
|
+
try {
|
|
226
|
+
const val = childRecord[field];
|
|
227
|
+
if (isStatusIndicatorLike(val)) return val;
|
|
228
|
+
} catch {
|
|
229
|
+
// Ignore getter errors
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
// Check one more level for container -> editor -> workingStatusIndicator
|
|
233
|
+
if (Array.isArray(childRecord.children)) {
|
|
234
|
+
for (const grandChild of childRecord.children) {
|
|
235
|
+
if (!grandChild || typeof grandChild !== "object") continue;
|
|
236
|
+
if (isStatusIndicatorLike(grandChild)) return grandChild;
|
|
237
|
+
const grandRecord = grandChild as Record<string, unknown>;
|
|
238
|
+
for (const field of knownFields) {
|
|
239
|
+
try {
|
|
240
|
+
const val = grandRecord[field];
|
|
241
|
+
if (isStatusIndicatorLike(val)) return val;
|
|
242
|
+
} catch {
|
|
243
|
+
// Ignore getter errors
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// Recurse into children array
|
|
251
|
+
for (const child of record.children) {
|
|
252
|
+
const found = findCompactionIndicator(child, depth + 1, seen);
|
|
253
|
+
if (found) return found;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// Recurse into layoutRoot (fullscreen ViewportTUI)
|
|
258
|
+
if (record.layoutRoot && typeof record.layoutRoot === "object") {
|
|
259
|
+
const found = findCompactionIndicator(record.layoutRoot, depth + 1, seen);
|
|
260
|
+
if (found) return found;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// Recurse into stack entries (VStack / HStack)
|
|
264
|
+
if (Array.isArray(record.entries)) {
|
|
265
|
+
for (const entry of record.entries) {
|
|
266
|
+
if (entry && typeof entry === "object") {
|
|
267
|
+
const comp = (entry as Record<string, unknown>).component ?? entry;
|
|
268
|
+
const found = findCompactionIndicator(comp, depth + 1, seen);
|
|
269
|
+
if (found) return found;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
return undefined;
|
|
275
|
+
}
|
package/src/text.ts
ADDED
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
import type { PiUiCustomTheme } from "./pi.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Terminal text primitives shared by every Repi plugin.
|
|
5
|
+
*
|
|
6
|
+
* A line handed to the TUI is measured in display columns, not string length: SGR sequences and
|
|
7
|
+
* combining marks count 0, East Asian wide characters and emoji count 2. Plugins previously kept
|
|
8
|
+
* two different implementations of this, so the widget and the settings menu disagreed about how
|
|
9
|
+
* wide a line was. This is the single place that walks terminal text.
|
|
10
|
+
*
|
|
11
|
+
* Only SGR styling may pass through. Cursor movement, OSC titles and other control sequences are
|
|
12
|
+
* dropped: a plugin must never move the cursor of the host's screen.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** Remove terminal control sequences and non-printable control characters from display text. */
|
|
16
|
+
export function sanitize(value?: string): string {
|
|
17
|
+
if (typeof value !== "string") {
|
|
18
|
+
return "";
|
|
19
|
+
}
|
|
20
|
+
// Stripping terminal control sequences is the point of this function.
|
|
21
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: OSC terminator
|
|
22
|
+
const osc = /\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g;
|
|
23
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: CSI parameters
|
|
24
|
+
const csi = /\x1b\[[0-9;?<=>]*[ -/]*[@-~]/g;
|
|
25
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: two-byte escapes
|
|
26
|
+
const esc = /\x1b[@-_]/g;
|
|
27
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: remaining control characters
|
|
28
|
+
const control = /[\x00-\x08\x0b-\x1f\x7f-\x9f]/g;
|
|
29
|
+
return value.replace(osc, "").replace(csi, "").replace(esc, "").replace(control, "");
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface DisplayToken {
|
|
33
|
+
readonly text: string;
|
|
34
|
+
/** Visible columns; 0 for an SGR style sequence. */
|
|
35
|
+
readonly width: number;
|
|
36
|
+
readonly sgr: boolean;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Grapheme segmentation is the same primitive the host renderer measures with, so a plugin line and
|
|
41
|
+
* the host's own width check always agree.
|
|
42
|
+
*/
|
|
43
|
+
const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Tokenize display text by visible width.
|
|
47
|
+
*
|
|
48
|
+
* SGR sequences are kept as zero-width tokens so `truncate`/`fitWidth` can preserve theme colours;
|
|
49
|
+
* every other escape or control sequence is dropped.
|
|
50
|
+
*/
|
|
51
|
+
function* displayTokens(value: string): Generator<DisplayToken> {
|
|
52
|
+
let index = 0;
|
|
53
|
+
while (index < value.length) {
|
|
54
|
+
const code = value.charCodeAt(index);
|
|
55
|
+
if (code === 0x1b) {
|
|
56
|
+
const next = value[index + 1];
|
|
57
|
+
if (next === "[") {
|
|
58
|
+
let end = index + 2;
|
|
59
|
+
while (end < value.length) {
|
|
60
|
+
const current = value.charCodeAt(end);
|
|
61
|
+
end++;
|
|
62
|
+
if (current >= 0x40 && current <= 0x7e) {
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const sequence = value.slice(index, end);
|
|
67
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: SGR sequence produced by theme.fg
|
|
68
|
+
if (sequence.endsWith("m") && /^\x1b\[[0-9;:?<=>]*m$/.test(sequence)) {
|
|
69
|
+
yield { text: sequence, width: 0, sgr: true };
|
|
70
|
+
}
|
|
71
|
+
index = end;
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
if (next === "]") {
|
|
75
|
+
// OSC: consume until BEL or ST; never forward it to the terminal.
|
|
76
|
+
let end = index + 2;
|
|
77
|
+
while (end < value.length) {
|
|
78
|
+
if (value.charCodeAt(end) === 0x07) {
|
|
79
|
+
end++;
|
|
80
|
+
break;
|
|
81
|
+
}
|
|
82
|
+
if (value.charCodeAt(end) === 0x1b && value[end + 1] === "\\") {
|
|
83
|
+
end += 2;
|
|
84
|
+
break;
|
|
85
|
+
}
|
|
86
|
+
end++;
|
|
87
|
+
}
|
|
88
|
+
index = end;
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
// Two-byte escape or a truncated sequence: drop both bytes.
|
|
92
|
+
index += next === undefined ? 1 : 2;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if ((code < 0x20 && code !== 0x09) || (code >= 0x7f && code <= 0x9f)) {
|
|
96
|
+
index++;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
// Visible run up to the next escape sequence; tabs are the host's three-column tab.
|
|
100
|
+
let end = index;
|
|
101
|
+
while (end < value.length && value.charCodeAt(end) !== 0x1b) {
|
|
102
|
+
end++;
|
|
103
|
+
}
|
|
104
|
+
const run = value
|
|
105
|
+
.slice(index, end)
|
|
106
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: remaining control characters
|
|
107
|
+
.replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, "")
|
|
108
|
+
.replace(/\t/g, " ");
|
|
109
|
+
for (const { segment } of graphemeSegmenter.segment(run)) {
|
|
110
|
+
yield { text: segment, width: graphemeWidth(segment), sgr: false };
|
|
111
|
+
}
|
|
112
|
+
index = end;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Visible width of a string, used to keep widget and inspector lines inside the terminal. */
|
|
117
|
+
export function displayWidth(value: string): number {
|
|
118
|
+
let width = 0;
|
|
119
|
+
for (const token of displayTokens(value)) {
|
|
120
|
+
width += token.width;
|
|
121
|
+
}
|
|
122
|
+
return width;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Truncate to a terminal width, not a string length.
|
|
127
|
+
*
|
|
128
|
+
* SGR sequences (the colours produced by `theme.fg`) are preserved; all other control sequences
|
|
129
|
+
* are dropped. Docs (`docs/tui.md`) require display width for every line an extension hands the
|
|
130
|
+
* TUI.
|
|
131
|
+
*/
|
|
132
|
+
export function truncate(value: string, max: number): string {
|
|
133
|
+
if (max <= 0) {
|
|
134
|
+
return "";
|
|
135
|
+
}
|
|
136
|
+
const tokens = [...displayTokens(value)];
|
|
137
|
+
const total = tokens.reduce((sum, token) => sum + token.width, 0);
|
|
138
|
+
if (total <= max) {
|
|
139
|
+
return tokens.map((token) => token.text).join("");
|
|
140
|
+
}
|
|
141
|
+
let width = 0;
|
|
142
|
+
let result = "";
|
|
143
|
+
for (const token of tokens) {
|
|
144
|
+
if (token.sgr) {
|
|
145
|
+
result += token.text;
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
if (width + token.width > max - 1) {
|
|
149
|
+
break;
|
|
150
|
+
}
|
|
151
|
+
width += token.width;
|
|
152
|
+
result += token.text;
|
|
153
|
+
}
|
|
154
|
+
return `${result.trimEnd()}…${result.includes("\x1b[") ? "\x1b[0m" : ""}`;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Pad a line to exactly `width` visible columns. */
|
|
158
|
+
export function fitWidth(value: string, width: number): string {
|
|
159
|
+
const clamped = truncate(value, Math.max(0, width));
|
|
160
|
+
return `${clamped}${" ".repeat(Math.max(0, width - displayWidth(clamped)))}`;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Left label with a right-aligned value, both inside `width` columns. */
|
|
164
|
+
export function alignRight(left: string, right: string, width: number): string {
|
|
165
|
+
const rightWidth = displayWidth(right);
|
|
166
|
+
const leftWidth = Math.max(0, width - rightWidth - 1);
|
|
167
|
+
return fitWidth(
|
|
168
|
+
`${fitWidth(left, leftWidth)}${" ".repeat(Math.max(1, width - leftWidth - rightWidth))}${right}`,
|
|
169
|
+
width,
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Wrap one logical line to a visible width, preserving SGR styling.
|
|
175
|
+
*
|
|
176
|
+
* The host renders every returned line on its own, so an SGR sequence cannot be left open across a
|
|
177
|
+
* wrap: each line closes the style it inherited and the next line reopens it.
|
|
178
|
+
*/
|
|
179
|
+
export function wrapDisplay(value: string, width: number): string[] {
|
|
180
|
+
if (width <= 0) {
|
|
181
|
+
return [""];
|
|
182
|
+
}
|
|
183
|
+
const result: string[] = [];
|
|
184
|
+
for (const logical of value.split("\n")) {
|
|
185
|
+
let line = "";
|
|
186
|
+
let lineWidth = 0;
|
|
187
|
+
let hasContent = false;
|
|
188
|
+
let activeSgr = "";
|
|
189
|
+
const push = (): void => {
|
|
190
|
+
result.push(activeSgr ? `${line.trimEnd()}\x1b[0m` : line.trimEnd());
|
|
191
|
+
line = activeSgr;
|
|
192
|
+
lineWidth = 0;
|
|
193
|
+
hasContent = false;
|
|
194
|
+
};
|
|
195
|
+
for (const token of displayTokens(logical)) {
|
|
196
|
+
if (token.sgr) {
|
|
197
|
+
activeSgr = applySgr(activeSgr, token.text);
|
|
198
|
+
line += token.text;
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
if (token.width > width) {
|
|
202
|
+
// A single glyph can be wider than the budget (a CJK character in a one-column line).
|
|
203
|
+
// A grapheme cannot be split, and emitting it would hand the host a line wider than the
|
|
204
|
+
// terminal, so the glyph is dropped rather than allowed to overflow.
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
if (lineWidth + token.width > width && hasContent) {
|
|
208
|
+
push();
|
|
209
|
+
}
|
|
210
|
+
line += token.text;
|
|
211
|
+
lineWidth += token.width;
|
|
212
|
+
hasContent = true;
|
|
213
|
+
}
|
|
214
|
+
result.push(activeSgr ? `${line.trimEnd()}\x1b[0m` : line.trimEnd());
|
|
215
|
+
}
|
|
216
|
+
return result;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** SGR params that only close styling; seeing one drops the carried prefix. */
|
|
220
|
+
const SGR_RESET_PARAMS = new Set(["0", "", "22", "23", "24", "25", "27", "28", "29", "39", "49"]);
|
|
221
|
+
|
|
222
|
+
/** Carry the styling that is still open after `sgr` so the next wrapped line can reopen it. */
|
|
223
|
+
function applySgr(active: string, sgr: string): string {
|
|
224
|
+
const params = sgr.slice(2, -1).split(";");
|
|
225
|
+
if (params.every((param) => SGR_RESET_PARAMS.has(param))) {
|
|
226
|
+
return "";
|
|
227
|
+
}
|
|
228
|
+
return `${active}${sgr}`;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** `theme.bold` is optional in the structural host contract. */
|
|
232
|
+
export function boldText(theme: PiUiCustomTheme | undefined, text: string): string {
|
|
233
|
+
if (!theme?.bold) {
|
|
234
|
+
return text;
|
|
235
|
+
}
|
|
236
|
+
try {
|
|
237
|
+
return theme.bold(text);
|
|
238
|
+
} catch {
|
|
239
|
+
return text;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** Clusters that occupy no cells at all: marks, joiners, variation selectors, hidden controls. */
|
|
244
|
+
const ZERO_WIDTH_CLUSTER = /^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Mark}|\p{Surrogate})+$/u;
|
|
245
|
+
/** Marks at the start of a cluster are stripped before the base character is measured. */
|
|
246
|
+
const LEADING_NON_PRINTING = /^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/u;
|
|
247
|
+
/** Marks that terminals still allocate a cell for when they are attached to a base character. */
|
|
248
|
+
const TERMINAL_SPACING_MARK = /^\p{Spacing_Mark}$/u;
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* `\p{RGI_Emoji}` needs the `v` flag. It is built lazily so a runtime without it falls back to a
|
|
252
|
+
* conservative pictographic test instead of failing to load the plugin.
|
|
253
|
+
*/
|
|
254
|
+
const RGI_EMOJI_PATTERN = "^(?:\\p{RGI_Emoji})$";
|
|
255
|
+
let rgiEmoji: RegExp | undefined;
|
|
256
|
+
function isRgiEmoji(segment: string): boolean {
|
|
257
|
+
if (rgiEmoji === undefined) {
|
|
258
|
+
try {
|
|
259
|
+
// The `v` flag is ES2024; the compiler target is ES2022, so it is only ever built here.
|
|
260
|
+
rgiEmoji = new RegExp(RGI_EMOJI_PATTERN, "v");
|
|
261
|
+
} catch {
|
|
262
|
+
rgiEmoji = /^(?:\p{Extended_Pictographic}|\p{Emoji_Presentation})/u;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
return rgiEmoji.test(segment);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Same pre-filter the host uses, so the expensive emoji regex only sees plausible clusters. */
|
|
269
|
+
function couldBeEmoji(segment: string): boolean {
|
|
270
|
+
const codePoint = segment.codePointAt(0) ?? 0;
|
|
271
|
+
return (
|
|
272
|
+
(codePoint >= 0x1f000 && codePoint <= 0x1fbff) ||
|
|
273
|
+
(codePoint >= 0x2300 && codePoint <= 0x23ff) ||
|
|
274
|
+
(codePoint >= 0x2600 && codePoint <= 0x27bf) ||
|
|
275
|
+
(codePoint >= 0x2b50 && codePoint <= 0x2b55) ||
|
|
276
|
+
segment.includes("\ufe0f") ||
|
|
277
|
+
segment.length > 2
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Visible width of one grapheme cluster, in terminal columns. */
|
|
282
|
+
function graphemeWidth(segment: string): number {
|
|
283
|
+
let printableAscii = segment.length > 0;
|
|
284
|
+
for (let index = 0; index < segment.length; index++) {
|
|
285
|
+
const code = segment.charCodeAt(index);
|
|
286
|
+
if (code < 0x20 || code > 0x7e) {
|
|
287
|
+
printableAscii = false;
|
|
288
|
+
break;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
if (printableAscii) {
|
|
292
|
+
return 1;
|
|
293
|
+
}
|
|
294
|
+
if (segment === "\t") {
|
|
295
|
+
return 3;
|
|
296
|
+
}
|
|
297
|
+
if (TERMINAL_SPACING_MARK.test(segment)) {
|
|
298
|
+
return [...segment].length;
|
|
299
|
+
}
|
|
300
|
+
if (ZERO_WIDTH_CLUSTER.test(segment)) {
|
|
301
|
+
return 0;
|
|
302
|
+
}
|
|
303
|
+
if (couldBeEmoji(segment) && isRgiEmoji(segment)) {
|
|
304
|
+
return 2;
|
|
305
|
+
}
|
|
306
|
+
const base = segment.replace(LEADING_NON_PRINTING, "");
|
|
307
|
+
const codePoint = base.codePointAt(0);
|
|
308
|
+
if (codePoint === undefined) {
|
|
309
|
+
return 0;
|
|
310
|
+
}
|
|
311
|
+
// Isolated regional indicators are still drawn two cells wide by most terminals.
|
|
312
|
+
if (codePoint >= 0x1f1e6 && codePoint <= 0x1f1ff) {
|
|
313
|
+
return 2;
|
|
314
|
+
}
|
|
315
|
+
return eastAsianWidth(codePoint);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** Wide and full-width code points (Unicode East_Asian_Width W/F), counted as two columns. */
|
|
319
|
+
function eastAsianWidth(codePoint: number): number {
|
|
320
|
+
return isWideCodePoint(codePoint) ? 2 : 1;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function isWideCodePoint(codePoint: number): boolean {
|
|
324
|
+
return (
|
|
325
|
+
(codePoint >= 0x1100 && codePoint <= 0x115f) ||
|
|
326
|
+
codePoint === 0x2329 ||
|
|
327
|
+
codePoint === 0x232a ||
|
|
328
|
+
(codePoint >= 0x2e80 && codePoint <= 0x303e) ||
|
|
329
|
+
(codePoint >= 0x3041 && codePoint <= 0x33ff) ||
|
|
330
|
+
(codePoint >= 0x3400 && codePoint <= 0x4dbf) ||
|
|
331
|
+
(codePoint >= 0x4e00 && codePoint <= 0x9fff) ||
|
|
332
|
+
(codePoint >= 0xa000 && codePoint <= 0xa4cf) ||
|
|
333
|
+
(codePoint >= 0xa960 && codePoint <= 0xa97f) ||
|
|
334
|
+
(codePoint >= 0xac00 && codePoint <= 0xd7a3) ||
|
|
335
|
+
(codePoint >= 0xf900 && codePoint <= 0xfaff) ||
|
|
336
|
+
(codePoint >= 0xfe10 && codePoint <= 0xfe19) ||
|
|
337
|
+
(codePoint >= 0xfe30 && codePoint <= 0xfe6f) ||
|
|
338
|
+
(codePoint >= 0xff00 && codePoint <= 0xff60) ||
|
|
339
|
+
(codePoint >= 0xffe0 && codePoint <= 0xffe6) ||
|
|
340
|
+
(codePoint >= 0x1b000 && codePoint <= 0x1b001) ||
|
|
341
|
+
(codePoint >= 0x1f200 && codePoint <= 0x1f251) ||
|
|
342
|
+
(codePoint >= 0x20000 && codePoint <= 0x3fffd)
|
|
343
|
+
);
|
|
344
|
+
}
|