@lenylvt/pi-tui 0.64.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 (127) hide show
  1. package/README.md +767 -0
  2. package/dist/autocomplete.d.ts +50 -0
  3. package/dist/autocomplete.d.ts.map +1 -0
  4. package/dist/autocomplete.js +623 -0
  5. package/dist/autocomplete.js.map +1 -0
  6. package/dist/components/box.d.ts +22 -0
  7. package/dist/components/box.d.ts.map +1 -0
  8. package/dist/components/box.js +104 -0
  9. package/dist/components/box.js.map +1 -0
  10. package/dist/components/cancellable-loader.d.ts +22 -0
  11. package/dist/components/cancellable-loader.d.ts.map +1 -0
  12. package/dist/components/cancellable-loader.js +35 -0
  13. package/dist/components/cancellable-loader.js.map +1 -0
  14. package/dist/components/editor.d.ts +244 -0
  15. package/dist/components/editor.d.ts.map +1 -0
  16. package/dist/components/editor.js +1861 -0
  17. package/dist/components/editor.js.map +1 -0
  18. package/dist/components/image.d.ts +28 -0
  19. package/dist/components/image.d.ts.map +1 -0
  20. package/dist/components/image.js +69 -0
  21. package/dist/components/image.js.map +1 -0
  22. package/dist/components/input.d.ts +37 -0
  23. package/dist/components/input.d.ts.map +1 -0
  24. package/dist/components/input.js +426 -0
  25. package/dist/components/input.js.map +1 -0
  26. package/dist/components/loader.d.ts +21 -0
  27. package/dist/components/loader.d.ts.map +1 -0
  28. package/dist/components/loader.js +49 -0
  29. package/dist/components/loader.js.map +1 -0
  30. package/dist/components/markdown.d.ts +95 -0
  31. package/dist/components/markdown.d.ts.map +1 -0
  32. package/dist/components/markdown.js +660 -0
  33. package/dist/components/markdown.js.map +1 -0
  34. package/dist/components/select-list.d.ts +50 -0
  35. package/dist/components/select-list.d.ts.map +1 -0
  36. package/dist/components/select-list.js +159 -0
  37. package/dist/components/select-list.js.map +1 -0
  38. package/dist/components/settings-list.d.ts +50 -0
  39. package/dist/components/settings-list.d.ts.map +1 -0
  40. package/dist/components/settings-list.js +185 -0
  41. package/dist/components/settings-list.js.map +1 -0
  42. package/dist/components/spacer.d.ts +12 -0
  43. package/dist/components/spacer.d.ts.map +1 -0
  44. package/dist/components/spacer.js +23 -0
  45. package/dist/components/spacer.js.map +1 -0
  46. package/dist/components/text.d.ts +19 -0
  47. package/dist/components/text.d.ts.map +1 -0
  48. package/dist/components/text.js +89 -0
  49. package/dist/components/text.js.map +1 -0
  50. package/dist/components/truncated-text.d.ts +13 -0
  51. package/dist/components/truncated-text.d.ts.map +1 -0
  52. package/dist/components/truncated-text.js +51 -0
  53. package/dist/components/truncated-text.js.map +1 -0
  54. package/dist/editor-component.d.ts +39 -0
  55. package/dist/editor-component.d.ts.map +1 -0
  56. package/dist/editor-component.js +2 -0
  57. package/dist/editor-component.js.map +1 -0
  58. package/dist/fuzzy.d.ts +16 -0
  59. package/dist/fuzzy.d.ts.map +1 -0
  60. package/dist/fuzzy.js +107 -0
  61. package/dist/fuzzy.js.map +1 -0
  62. package/dist/index.d.ts +23 -0
  63. package/dist/index.d.ts.map +1 -0
  64. package/dist/index.js +32 -0
  65. package/dist/index.js.map +1 -0
  66. package/dist/keybindings.d.ts +193 -0
  67. package/dist/keybindings.d.ts.map +1 -0
  68. package/dist/keybindings.js +174 -0
  69. package/dist/keybindings.js.map +1 -0
  70. package/dist/keys.d.ts +170 -0
  71. package/dist/keys.d.ts.map +1 -0
  72. package/dist/keys.js +1124 -0
  73. package/dist/keys.js.map +1 -0
  74. package/dist/kill-ring.d.ts +28 -0
  75. package/dist/kill-ring.d.ts.map +1 -0
  76. package/dist/kill-ring.js +44 -0
  77. package/dist/kill-ring.js.map +1 -0
  78. package/dist/stdin-buffer.d.ts +48 -0
  79. package/dist/stdin-buffer.d.ts.map +1 -0
  80. package/dist/stdin-buffer.js +317 -0
  81. package/dist/stdin-buffer.js.map +1 -0
  82. package/dist/terminal-image.d.ts +68 -0
  83. package/dist/terminal-image.d.ts.map +1 -0
  84. package/dist/terminal-image.js +288 -0
  85. package/dist/terminal-image.js.map +1 -0
  86. package/dist/terminal.d.ts +84 -0
  87. package/dist/terminal.d.ts.map +1 -0
  88. package/dist/terminal.js +285 -0
  89. package/dist/terminal.js.map +1 -0
  90. package/dist/tui.d.ts +218 -0
  91. package/dist/tui.d.ts.map +1 -0
  92. package/dist/tui.js +966 -0
  93. package/dist/tui.js.map +1 -0
  94. package/dist/undo-stack.d.ts +17 -0
  95. package/dist/undo-stack.d.ts.map +1 -0
  96. package/dist/undo-stack.js +25 -0
  97. package/dist/undo-stack.js.map +1 -0
  98. package/dist/utils.d.ts +78 -0
  99. package/dist/utils.d.ts.map +1 -0
  100. package/dist/utils.js +960 -0
  101. package/dist/utils.js.map +1 -0
  102. package/package.json +55 -0
  103. package/src/autocomplete.ts +771 -0
  104. package/src/components/box.ts +137 -0
  105. package/src/components/cancellable-loader.ts +40 -0
  106. package/src/components/editor.ts +2230 -0
  107. package/src/components/image.ts +104 -0
  108. package/src/components/input.ts +503 -0
  109. package/src/components/loader.ts +55 -0
  110. package/src/components/markdown.ts +820 -0
  111. package/src/components/select-list.ts +229 -0
  112. package/src/components/settings-list.ts +250 -0
  113. package/src/components/spacer.ts +28 -0
  114. package/src/components/text.ts +106 -0
  115. package/src/components/truncated-text.ts +65 -0
  116. package/src/editor-component.ts +74 -0
  117. package/src/fuzzy.ts +133 -0
  118. package/src/index.ts +104 -0
  119. package/src/keybindings.ts +244 -0
  120. package/src/keys.ts +1356 -0
  121. package/src/kill-ring.ts +46 -0
  122. package/src/stdin-buffer.ts +386 -0
  123. package/src/terminal-image.ts +381 -0
  124. package/src/terminal.ts +360 -0
  125. package/src/tui.ts +1200 -0
  126. package/src/undo-stack.ts +28 -0
  127. package/src/utils.ts +1068 -0
package/src/utils.ts ADDED
@@ -0,0 +1,1068 @@
1
+ import { eastAsianWidth } from "get-east-asian-width";
2
+
3
+ // Grapheme segmenter (shared instance)
4
+ const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
5
+
6
+ /**
7
+ * Get the shared grapheme segmenter instance.
8
+ */
9
+ export function getSegmenter(): Intl.Segmenter {
10
+ return segmenter;
11
+ }
12
+
13
+ /**
14
+ * Check if a grapheme cluster (after segmentation) could possibly be an RGI emoji.
15
+ * This is a fast heuristic to avoid the expensive rgiEmojiRegex test.
16
+ * The tested Unicode blocks are deliberately broad to account for future
17
+ * Unicode additions.
18
+ */
19
+ function couldBeEmoji(segment: string): boolean {
20
+ const cp = segment.codePointAt(0)!;
21
+ return (
22
+ (cp >= 0x1f000 && cp <= 0x1fbff) || // Emoji and Pictograph
23
+ (cp >= 0x2300 && cp <= 0x23ff) || // Misc technical
24
+ (cp >= 0x2600 && cp <= 0x27bf) || // Misc symbols, dingbats
25
+ (cp >= 0x2b50 && cp <= 0x2b55) || // Specific stars/circles
26
+ segment.includes("\uFE0F") || // Contains VS16 (emoji presentation selector)
27
+ segment.length > 2 // Multi-codepoint sequences (ZWJ, skin tones, etc.)
28
+ );
29
+ }
30
+
31
+ // Regexes for character classification (same as string-width library)
32
+ const zeroWidthRegex = /^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Mark}|\p{Surrogate})+$/v;
33
+ const leadingNonPrintingRegex = /^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v;
34
+ const rgiEmojiRegex = /^\p{RGI_Emoji}$/v;
35
+
36
+ // Cache for non-ASCII strings
37
+ const WIDTH_CACHE_SIZE = 512;
38
+ const widthCache = new Map<string, number>();
39
+
40
+ function isPrintableAscii(str: string): boolean {
41
+ for (let i = 0; i < str.length; i++) {
42
+ const code = str.charCodeAt(i);
43
+ if (code < 0x20 || code > 0x7e) {
44
+ return false;
45
+ }
46
+ }
47
+ return true;
48
+ }
49
+
50
+ function truncateFragmentToWidth(text: string, maxWidth: number): { text: string; width: number } {
51
+ if (maxWidth <= 0 || text.length === 0) {
52
+ return { text: "", width: 0 };
53
+ }
54
+
55
+ if (isPrintableAscii(text)) {
56
+ const clipped = text.slice(0, maxWidth);
57
+ return { text: clipped, width: clipped.length };
58
+ }
59
+
60
+ const hasAnsi = text.includes("\x1b");
61
+ const hasTabs = text.includes("\t");
62
+ if (!hasAnsi && !hasTabs) {
63
+ let result = "";
64
+ let width = 0;
65
+ for (const { segment } of segmenter.segment(text)) {
66
+ const w = graphemeWidth(segment);
67
+ if (width + w > maxWidth) {
68
+ break;
69
+ }
70
+ result += segment;
71
+ width += w;
72
+ }
73
+ return { text: result, width };
74
+ }
75
+
76
+ let result = "";
77
+ let width = 0;
78
+ let i = 0;
79
+ let pendingAnsi = "";
80
+
81
+ while (i < text.length) {
82
+ const ansi = extractAnsiCode(text, i);
83
+ if (ansi) {
84
+ pendingAnsi += ansi.code;
85
+ i += ansi.length;
86
+ continue;
87
+ }
88
+
89
+ if (text[i] === "\t") {
90
+ if (width + 3 > maxWidth) {
91
+ break;
92
+ }
93
+ if (pendingAnsi) {
94
+ result += pendingAnsi;
95
+ pendingAnsi = "";
96
+ }
97
+ result += "\t";
98
+ width += 3;
99
+ i++;
100
+ continue;
101
+ }
102
+
103
+ let end = i;
104
+ while (end < text.length && text[end] !== "\t") {
105
+ const nextAnsi = extractAnsiCode(text, end);
106
+ if (nextAnsi) {
107
+ break;
108
+ }
109
+ end++;
110
+ }
111
+
112
+ for (const { segment } of segmenter.segment(text.slice(i, end))) {
113
+ const w = graphemeWidth(segment);
114
+ if (width + w > maxWidth) {
115
+ return { text: result, width };
116
+ }
117
+ if (pendingAnsi) {
118
+ result += pendingAnsi;
119
+ pendingAnsi = "";
120
+ }
121
+ result += segment;
122
+ width += w;
123
+ }
124
+ i = end;
125
+ }
126
+
127
+ return { text: result, width };
128
+ }
129
+
130
+ function finalizeTruncatedResult(
131
+ prefix: string,
132
+ prefixWidth: number,
133
+ ellipsis: string,
134
+ ellipsisWidth: number,
135
+ maxWidth: number,
136
+ pad: boolean,
137
+ ): string {
138
+ const reset = "\x1b[0m";
139
+ const visibleWidth = prefixWidth + ellipsisWidth;
140
+ let result: string;
141
+
142
+ if (ellipsis.length > 0) {
143
+ result = `${prefix}${reset}${ellipsis}${reset}`;
144
+ } else {
145
+ result = `${prefix}${reset}`;
146
+ }
147
+
148
+ return pad ? result + " ".repeat(Math.max(0, maxWidth - visibleWidth)) : result;
149
+ }
150
+
151
+ /**
152
+ * Calculate the terminal width of a single grapheme cluster.
153
+ * Based on code from the string-width library, but includes a possible-emoji
154
+ * check to avoid running the RGI_Emoji regex unnecessarily.
155
+ */
156
+ function graphemeWidth(segment: string): number {
157
+ // Zero-width clusters
158
+ if (zeroWidthRegex.test(segment)) {
159
+ return 0;
160
+ }
161
+
162
+ // Emoji check with pre-filter
163
+ if (couldBeEmoji(segment) && rgiEmojiRegex.test(segment)) {
164
+ return 2;
165
+ }
166
+
167
+ // Get base visible codepoint
168
+ const base = segment.replace(leadingNonPrintingRegex, "");
169
+ const cp = base.codePointAt(0);
170
+ if (cp === undefined) {
171
+ return 0;
172
+ }
173
+
174
+ // Regional indicator symbols (U+1F1E6..U+1F1FF) are often rendered as
175
+ // full-width emoji in terminals, even when isolated during streaming.
176
+ // Keep width conservative (2) to avoid terminal auto-wrap drift artifacts.
177
+ if (cp >= 0x1f1e6 && cp <= 0x1f1ff) {
178
+ return 2;
179
+ }
180
+
181
+ let width = eastAsianWidth(cp);
182
+
183
+ // Trailing halfwidth/fullwidth forms
184
+ if (segment.length > 1) {
185
+ for (const char of segment.slice(1)) {
186
+ const c = char.codePointAt(0)!;
187
+ if (c >= 0xff00 && c <= 0xffef) {
188
+ width += eastAsianWidth(c);
189
+ }
190
+ }
191
+ }
192
+
193
+ return width;
194
+ }
195
+
196
+ /**
197
+ * Calculate the visible width of a string in terminal columns.
198
+ */
199
+ export function visibleWidth(str: string): number {
200
+ if (str.length === 0) {
201
+ return 0;
202
+ }
203
+
204
+ // Fast path: pure ASCII printable
205
+ if (isPrintableAscii(str)) {
206
+ return str.length;
207
+ }
208
+
209
+ // Check cache
210
+ const cached = widthCache.get(str);
211
+ if (cached !== undefined) {
212
+ return cached;
213
+ }
214
+
215
+ // Normalize: tabs to 3 spaces, strip ANSI escape codes
216
+ let clean = str;
217
+ if (str.includes("\t")) {
218
+ clean = clean.replace(/\t/g, " ");
219
+ }
220
+ if (clean.includes("\x1b")) {
221
+ // Strip supported ANSI/OSC/APC escape sequences in one pass.
222
+ // This covers CSI styling/cursor codes, OSC hyperlinks and prompt markers,
223
+ // and APC sequences like CURSOR_MARKER.
224
+ let stripped = "";
225
+ let i = 0;
226
+ while (i < clean.length) {
227
+ const ansi = extractAnsiCode(clean, i);
228
+ if (ansi) {
229
+ i += ansi.length;
230
+ continue;
231
+ }
232
+ stripped += clean[i];
233
+ i++;
234
+ }
235
+ clean = stripped;
236
+ }
237
+
238
+ // Calculate width
239
+ let width = 0;
240
+ for (const { segment } of segmenter.segment(clean)) {
241
+ width += graphemeWidth(segment);
242
+ }
243
+
244
+ // Cache result
245
+ if (widthCache.size >= WIDTH_CACHE_SIZE) {
246
+ const firstKey = widthCache.keys().next().value;
247
+ if (firstKey !== undefined) {
248
+ widthCache.delete(firstKey);
249
+ }
250
+ }
251
+ widthCache.set(str, width);
252
+
253
+ return width;
254
+ }
255
+
256
+ /**
257
+ * Extract ANSI escape sequences from a string at the given position.
258
+ */
259
+ export function extractAnsiCode(str: string, pos: number): { code: string; length: number } | null {
260
+ if (pos >= str.length || str[pos] !== "\x1b") return null;
261
+
262
+ const next = str[pos + 1];
263
+
264
+ // CSI sequence: ESC [ ... m/G/K/H/J
265
+ if (next === "[") {
266
+ let j = pos + 2;
267
+ while (j < str.length && !/[mGKHJ]/.test(str[j]!)) j++;
268
+ if (j < str.length) return { code: str.substring(pos, j + 1), length: j + 1 - pos };
269
+ return null;
270
+ }
271
+
272
+ // OSC sequence: ESC ] ... BEL or ESC ] ... ST (ESC \)
273
+ // Used for hyperlinks (OSC 8), window titles, etc.
274
+ if (next === "]") {
275
+ let j = pos + 2;
276
+ while (j < str.length) {
277
+ if (str[j] === "\x07") return { code: str.substring(pos, j + 1), length: j + 1 - pos };
278
+ if (str[j] === "\x1b" && str[j + 1] === "\\") return { code: str.substring(pos, j + 2), length: j + 2 - pos };
279
+ j++;
280
+ }
281
+ return null;
282
+ }
283
+
284
+ // APC sequence: ESC _ ... BEL or ESC _ ... ST (ESC \)
285
+ // Used for cursor marker and application-specific commands
286
+ if (next === "_") {
287
+ let j = pos + 2;
288
+ while (j < str.length) {
289
+ if (str[j] === "\x07") return { code: str.substring(pos, j + 1), length: j + 1 - pos };
290
+ if (str[j] === "\x1b" && str[j + 1] === "\\") return { code: str.substring(pos, j + 2), length: j + 2 - pos };
291
+ j++;
292
+ }
293
+ return null;
294
+ }
295
+
296
+ return null;
297
+ }
298
+
299
+ /**
300
+ * Track active ANSI SGR codes to preserve styling across line breaks.
301
+ */
302
+ class AnsiCodeTracker {
303
+ // Track individual attributes separately so we can reset them specifically
304
+ private bold = false;
305
+ private dim = false;
306
+ private italic = false;
307
+ private underline = false;
308
+ private blink = false;
309
+ private inverse = false;
310
+ private hidden = false;
311
+ private strikethrough = false;
312
+ private fgColor: string | null = null; // Stores the full code like "31" or "38;5;240"
313
+ private bgColor: string | null = null; // Stores the full code like "41" or "48;5;240"
314
+
315
+ process(ansiCode: string): void {
316
+ if (!ansiCode.endsWith("m")) {
317
+ return;
318
+ }
319
+
320
+ // Extract the parameters between \x1b[ and m
321
+ const match = ansiCode.match(/\x1b\[([\d;]*)m/);
322
+ if (!match) return;
323
+
324
+ const params = match[1];
325
+ if (params === "" || params === "0") {
326
+ // Full reset
327
+ this.reset();
328
+ return;
329
+ }
330
+
331
+ // Parse parameters (can be semicolon-separated)
332
+ const parts = params.split(";");
333
+ let i = 0;
334
+ while (i < parts.length) {
335
+ const code = Number.parseInt(parts[i], 10);
336
+
337
+ // Handle 256-color and RGB codes which consume multiple parameters
338
+ if (code === 38 || code === 48) {
339
+ // 38;5;N (256 color fg) or 38;2;R;G;B (RGB fg)
340
+ // 48;5;N (256 color bg) or 48;2;R;G;B (RGB bg)
341
+ if (parts[i + 1] === "5" && parts[i + 2] !== undefined) {
342
+ // 256 color: 38;5;N or 48;5;N
343
+ const colorCode = `${parts[i]};${parts[i + 1]};${parts[i + 2]}`;
344
+ if (code === 38) {
345
+ this.fgColor = colorCode;
346
+ } else {
347
+ this.bgColor = colorCode;
348
+ }
349
+ i += 3;
350
+ continue;
351
+ } else if (parts[i + 1] === "2" && parts[i + 4] !== undefined) {
352
+ // RGB color: 38;2;R;G;B or 48;2;R;G;B
353
+ const colorCode = `${parts[i]};${parts[i + 1]};${parts[i + 2]};${parts[i + 3]};${parts[i + 4]}`;
354
+ if (code === 38) {
355
+ this.fgColor = colorCode;
356
+ } else {
357
+ this.bgColor = colorCode;
358
+ }
359
+ i += 5;
360
+ continue;
361
+ }
362
+ }
363
+
364
+ // Standard SGR codes
365
+ switch (code) {
366
+ case 0:
367
+ this.reset();
368
+ break;
369
+ case 1:
370
+ this.bold = true;
371
+ break;
372
+ case 2:
373
+ this.dim = true;
374
+ break;
375
+ case 3:
376
+ this.italic = true;
377
+ break;
378
+ case 4:
379
+ this.underline = true;
380
+ break;
381
+ case 5:
382
+ this.blink = true;
383
+ break;
384
+ case 7:
385
+ this.inverse = true;
386
+ break;
387
+ case 8:
388
+ this.hidden = true;
389
+ break;
390
+ case 9:
391
+ this.strikethrough = true;
392
+ break;
393
+ case 21:
394
+ this.bold = false;
395
+ break; // Some terminals
396
+ case 22:
397
+ this.bold = false;
398
+ this.dim = false;
399
+ break;
400
+ case 23:
401
+ this.italic = false;
402
+ break;
403
+ case 24:
404
+ this.underline = false;
405
+ break;
406
+ case 25:
407
+ this.blink = false;
408
+ break;
409
+ case 27:
410
+ this.inverse = false;
411
+ break;
412
+ case 28:
413
+ this.hidden = false;
414
+ break;
415
+ case 29:
416
+ this.strikethrough = false;
417
+ break;
418
+ case 39:
419
+ this.fgColor = null;
420
+ break; // Default fg
421
+ case 49:
422
+ this.bgColor = null;
423
+ break; // Default bg
424
+ default:
425
+ // Standard foreground colors 30-37, 90-97
426
+ if ((code >= 30 && code <= 37) || (code >= 90 && code <= 97)) {
427
+ this.fgColor = String(code);
428
+ }
429
+ // Standard background colors 40-47, 100-107
430
+ else if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107)) {
431
+ this.bgColor = String(code);
432
+ }
433
+ break;
434
+ }
435
+ i++;
436
+ }
437
+ }
438
+
439
+ private reset(): void {
440
+ this.bold = false;
441
+ this.dim = false;
442
+ this.italic = false;
443
+ this.underline = false;
444
+ this.blink = false;
445
+ this.inverse = false;
446
+ this.hidden = false;
447
+ this.strikethrough = false;
448
+ this.fgColor = null;
449
+ this.bgColor = null;
450
+ }
451
+
452
+ /** Clear all state for reuse. */
453
+ clear(): void {
454
+ this.reset();
455
+ }
456
+
457
+ getActiveCodes(): string {
458
+ const codes: string[] = [];
459
+ if (this.bold) codes.push("1");
460
+ if (this.dim) codes.push("2");
461
+ if (this.italic) codes.push("3");
462
+ if (this.underline) codes.push("4");
463
+ if (this.blink) codes.push("5");
464
+ if (this.inverse) codes.push("7");
465
+ if (this.hidden) codes.push("8");
466
+ if (this.strikethrough) codes.push("9");
467
+ if (this.fgColor) codes.push(this.fgColor);
468
+ if (this.bgColor) codes.push(this.bgColor);
469
+
470
+ if (codes.length === 0) return "";
471
+ return `\x1b[${codes.join(";")}m`;
472
+ }
473
+
474
+ hasActiveCodes(): boolean {
475
+ return (
476
+ this.bold ||
477
+ this.dim ||
478
+ this.italic ||
479
+ this.underline ||
480
+ this.blink ||
481
+ this.inverse ||
482
+ this.hidden ||
483
+ this.strikethrough ||
484
+ this.fgColor !== null ||
485
+ this.bgColor !== null
486
+ );
487
+ }
488
+
489
+ /**
490
+ * Get reset codes for attributes that need to be turned off at line end,
491
+ * specifically underline which bleeds into padding.
492
+ * Returns empty string if no problematic attributes are active.
493
+ */
494
+ getLineEndReset(): string {
495
+ // Only underline causes visual bleeding into padding
496
+ // Other attributes like colors don't visually bleed to padding
497
+ if (this.underline) {
498
+ return "\x1b[24m"; // Underline off only
499
+ }
500
+ return "";
501
+ }
502
+ }
503
+
504
+ function updateTrackerFromText(text: string, tracker: AnsiCodeTracker): void {
505
+ let i = 0;
506
+ while (i < text.length) {
507
+ const ansiResult = extractAnsiCode(text, i);
508
+ if (ansiResult) {
509
+ tracker.process(ansiResult.code);
510
+ i += ansiResult.length;
511
+ } else {
512
+ i++;
513
+ }
514
+ }
515
+ }
516
+
517
+ /**
518
+ * Split text into words while keeping ANSI codes attached.
519
+ */
520
+ function splitIntoTokensWithAnsi(text: string): string[] {
521
+ const tokens: string[] = [];
522
+ let current = "";
523
+ let pendingAnsi = ""; // ANSI codes waiting to be attached to next visible content
524
+ let inWhitespace = false;
525
+ let i = 0;
526
+
527
+ while (i < text.length) {
528
+ const ansiResult = extractAnsiCode(text, i);
529
+ if (ansiResult) {
530
+ // Hold ANSI codes separately - they'll be attached to the next visible char
531
+ pendingAnsi += ansiResult.code;
532
+ i += ansiResult.length;
533
+ continue;
534
+ }
535
+
536
+ const char = text[i];
537
+ const charIsSpace = char === " ";
538
+
539
+ if (charIsSpace !== inWhitespace && current) {
540
+ // Switching between whitespace and non-whitespace, push current token
541
+ tokens.push(current);
542
+ current = "";
543
+ }
544
+
545
+ // Attach any pending ANSI codes to this visible character
546
+ if (pendingAnsi) {
547
+ current += pendingAnsi;
548
+ pendingAnsi = "";
549
+ }
550
+
551
+ inWhitespace = charIsSpace;
552
+ current += char;
553
+ i++;
554
+ }
555
+
556
+ // Handle any remaining pending ANSI codes (attach to last token)
557
+ if (pendingAnsi) {
558
+ current += pendingAnsi;
559
+ }
560
+
561
+ if (current) {
562
+ tokens.push(current);
563
+ }
564
+
565
+ return tokens;
566
+ }
567
+
568
+ /**
569
+ * Wrap text with ANSI codes preserved.
570
+ *
571
+ * ONLY does word wrapping - NO padding, NO background colors.
572
+ * Returns lines where each line is <= width visible chars.
573
+ * Active ANSI codes are preserved across line breaks.
574
+ *
575
+ * @param text - Text to wrap (may contain ANSI codes and newlines)
576
+ * @param width - Maximum visible width per line
577
+ * @returns Array of wrapped lines (NOT padded to width)
578
+ */
579
+ export function wrapTextWithAnsi(text: string, width: number): string[] {
580
+ if (!text) {
581
+ return [""];
582
+ }
583
+
584
+ // Handle newlines by processing each line separately
585
+ // Track ANSI state across lines so styles carry over after literal newlines
586
+ const inputLines = text.split("\n");
587
+ const result: string[] = [];
588
+ const tracker = new AnsiCodeTracker();
589
+
590
+ for (const inputLine of inputLines) {
591
+ // Prepend active ANSI codes from previous lines (except for first line)
592
+ const prefix = result.length > 0 ? tracker.getActiveCodes() : "";
593
+ result.push(...wrapSingleLine(prefix + inputLine, width));
594
+ // Update tracker with codes from this line for next iteration
595
+ updateTrackerFromText(inputLine, tracker);
596
+ }
597
+
598
+ return result.length > 0 ? result : [""];
599
+ }
600
+
601
+ function wrapSingleLine(line: string, width: number): string[] {
602
+ if (!line) {
603
+ return [""];
604
+ }
605
+
606
+ const visibleLength = visibleWidth(line);
607
+ if (visibleLength <= width) {
608
+ return [line];
609
+ }
610
+
611
+ const wrapped: string[] = [];
612
+ const tracker = new AnsiCodeTracker();
613
+ const tokens = splitIntoTokensWithAnsi(line);
614
+
615
+ let currentLine = "";
616
+ let currentVisibleLength = 0;
617
+
618
+ for (const token of tokens) {
619
+ const tokenVisibleLength = visibleWidth(token);
620
+ const isWhitespace = token.trim() === "";
621
+
622
+ // Token itself is too long - break it character by character
623
+ if (tokenVisibleLength > width && !isWhitespace) {
624
+ if (currentLine) {
625
+ // Add specific reset for underline only (preserves background)
626
+ const lineEndReset = tracker.getLineEndReset();
627
+ if (lineEndReset) {
628
+ currentLine += lineEndReset;
629
+ }
630
+ wrapped.push(currentLine);
631
+ currentLine = "";
632
+ currentVisibleLength = 0;
633
+ }
634
+
635
+ // Break long token - breakLongWord handles its own resets
636
+ const broken = breakLongWord(token, width, tracker);
637
+ wrapped.push(...broken.slice(0, -1));
638
+ currentLine = broken[broken.length - 1];
639
+ currentVisibleLength = visibleWidth(currentLine);
640
+ continue;
641
+ }
642
+
643
+ // Check if adding this token would exceed width
644
+ const totalNeeded = currentVisibleLength + tokenVisibleLength;
645
+
646
+ if (totalNeeded > width && currentVisibleLength > 0) {
647
+ // Trim trailing whitespace, then add underline reset (not full reset, to preserve background)
648
+ let lineToWrap = currentLine.trimEnd();
649
+ const lineEndReset = tracker.getLineEndReset();
650
+ if (lineEndReset) {
651
+ lineToWrap += lineEndReset;
652
+ }
653
+ wrapped.push(lineToWrap);
654
+ if (isWhitespace) {
655
+ // Don't start new line with whitespace
656
+ currentLine = tracker.getActiveCodes();
657
+ currentVisibleLength = 0;
658
+ } else {
659
+ currentLine = tracker.getActiveCodes() + token;
660
+ currentVisibleLength = tokenVisibleLength;
661
+ }
662
+ } else {
663
+ // Add to current line
664
+ currentLine += token;
665
+ currentVisibleLength += tokenVisibleLength;
666
+ }
667
+
668
+ updateTrackerFromText(token, tracker);
669
+ }
670
+
671
+ if (currentLine) {
672
+ // No reset at end of final line - let caller handle it
673
+ wrapped.push(currentLine);
674
+ }
675
+
676
+ // Trailing whitespace can cause lines to exceed the requested width
677
+ return wrapped.length > 0 ? wrapped.map((line) => line.trimEnd()) : [""];
678
+ }
679
+
680
+ const PUNCTUATION_REGEX = /[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;
681
+
682
+ /**
683
+ * Check if a character is whitespace.
684
+ */
685
+ export function isWhitespaceChar(char: string): boolean {
686
+ return /\s/.test(char);
687
+ }
688
+
689
+ /**
690
+ * Check if a character is punctuation.
691
+ */
692
+ export function isPunctuationChar(char: string): boolean {
693
+ return PUNCTUATION_REGEX.test(char);
694
+ }
695
+
696
+ function breakLongWord(word: string, width: number, tracker: AnsiCodeTracker): string[] {
697
+ const lines: string[] = [];
698
+ let currentLine = tracker.getActiveCodes();
699
+ let currentWidth = 0;
700
+
701
+ // First, separate ANSI codes from visible content
702
+ // We need to handle ANSI codes specially since they're not graphemes
703
+ let i = 0;
704
+ const segments: Array<{ type: "ansi" | "grapheme"; value: string }> = [];
705
+
706
+ while (i < word.length) {
707
+ const ansiResult = extractAnsiCode(word, i);
708
+ if (ansiResult) {
709
+ segments.push({ type: "ansi", value: ansiResult.code });
710
+ i += ansiResult.length;
711
+ } else {
712
+ // Find the next ANSI code or end of string
713
+ let end = i;
714
+ while (end < word.length) {
715
+ const nextAnsi = extractAnsiCode(word, end);
716
+ if (nextAnsi) break;
717
+ end++;
718
+ }
719
+ // Segment this non-ANSI portion into graphemes
720
+ const textPortion = word.slice(i, end);
721
+ for (const seg of segmenter.segment(textPortion)) {
722
+ segments.push({ type: "grapheme", value: seg.segment });
723
+ }
724
+ i = end;
725
+ }
726
+ }
727
+
728
+ // Now process segments
729
+ for (const seg of segments) {
730
+ if (seg.type === "ansi") {
731
+ currentLine += seg.value;
732
+ tracker.process(seg.value);
733
+ continue;
734
+ }
735
+
736
+ const grapheme = seg.value;
737
+ // Skip empty graphemes to avoid issues with string-width calculation
738
+ if (!grapheme) continue;
739
+
740
+ const graphemeWidth = visibleWidth(grapheme);
741
+
742
+ if (currentWidth + graphemeWidth > width) {
743
+ // Add specific reset for underline only (preserves background)
744
+ const lineEndReset = tracker.getLineEndReset();
745
+ if (lineEndReset) {
746
+ currentLine += lineEndReset;
747
+ }
748
+ lines.push(currentLine);
749
+ currentLine = tracker.getActiveCodes();
750
+ currentWidth = 0;
751
+ }
752
+
753
+ currentLine += grapheme;
754
+ currentWidth += graphemeWidth;
755
+ }
756
+
757
+ if (currentLine) {
758
+ // No reset at end of final segment - caller handles continuation
759
+ lines.push(currentLine);
760
+ }
761
+
762
+ return lines.length > 0 ? lines : [""];
763
+ }
764
+
765
+ /**
766
+ * Apply background color to a line, padding to full width.
767
+ *
768
+ * @param line - Line of text (may contain ANSI codes)
769
+ * @param width - Total width to pad to
770
+ * @param bgFn - Background color function
771
+ * @returns Line with background applied and padded to width
772
+ */
773
+ export function applyBackgroundToLine(line: string, width: number, bgFn: (text: string) => string): string {
774
+ // Calculate padding needed
775
+ const visibleLen = visibleWidth(line);
776
+ const paddingNeeded = Math.max(0, width - visibleLen);
777
+ const padding = " ".repeat(paddingNeeded);
778
+
779
+ // Apply background to content + padding
780
+ const withPadding = line + padding;
781
+ return bgFn(withPadding);
782
+ }
783
+
784
+ /**
785
+ * Truncate text to fit within a maximum visible width, adding ellipsis if needed.
786
+ * Optionally pad with spaces to reach exactly maxWidth.
787
+ * Properly handles ANSI escape codes (they don't count toward width).
788
+ *
789
+ * @param text - Text to truncate (may contain ANSI codes)
790
+ * @param maxWidth - Maximum visible width
791
+ * @param ellipsis - Ellipsis string to append when truncating (default: "...")
792
+ * @param pad - If true, pad result with spaces to exactly maxWidth (default: false)
793
+ * @returns Truncated text, optionally padded to exactly maxWidth
794
+ */
795
+ export function truncateToWidth(
796
+ text: string,
797
+ maxWidth: number,
798
+ ellipsis: string = "...",
799
+ pad: boolean = false,
800
+ ): string {
801
+ if (maxWidth <= 0) {
802
+ return "";
803
+ }
804
+
805
+ if (text.length === 0) {
806
+ return pad ? " ".repeat(maxWidth) : "";
807
+ }
808
+
809
+ const ellipsisWidth = visibleWidth(ellipsis);
810
+ if (ellipsisWidth >= maxWidth) {
811
+ const textWidth = visibleWidth(text);
812
+ if (textWidth <= maxWidth) {
813
+ return pad ? text + " ".repeat(maxWidth - textWidth) : text;
814
+ }
815
+
816
+ const clippedEllipsis = truncateFragmentToWidth(ellipsis, maxWidth);
817
+ if (clippedEllipsis.width === 0) {
818
+ return pad ? " ".repeat(maxWidth) : "";
819
+ }
820
+ return finalizeTruncatedResult("", 0, clippedEllipsis.text, clippedEllipsis.width, maxWidth, pad);
821
+ }
822
+
823
+ if (isPrintableAscii(text)) {
824
+ if (text.length <= maxWidth) {
825
+ return pad ? text + " ".repeat(maxWidth - text.length) : text;
826
+ }
827
+ const targetWidth = maxWidth - ellipsisWidth;
828
+ return finalizeTruncatedResult(text.slice(0, targetWidth), targetWidth, ellipsis, ellipsisWidth, maxWidth, pad);
829
+ }
830
+
831
+ const targetWidth = maxWidth - ellipsisWidth;
832
+ let result = "";
833
+ let pendingAnsi = "";
834
+ let visibleSoFar = 0;
835
+ let keptWidth = 0;
836
+ let keepContiguousPrefix = true;
837
+ let overflowed = false;
838
+ let exhaustedInput = false;
839
+ const hasAnsi = text.includes("\x1b");
840
+ const hasTabs = text.includes("\t");
841
+
842
+ if (!hasAnsi && !hasTabs) {
843
+ for (const { segment } of segmenter.segment(text)) {
844
+ const width = graphemeWidth(segment);
845
+ if (keepContiguousPrefix && keptWidth + width <= targetWidth) {
846
+ result += segment;
847
+ keptWidth += width;
848
+ } else {
849
+ keepContiguousPrefix = false;
850
+ }
851
+ visibleSoFar += width;
852
+ if (visibleSoFar > maxWidth) {
853
+ overflowed = true;
854
+ break;
855
+ }
856
+ }
857
+ exhaustedInput = !overflowed;
858
+ } else {
859
+ let i = 0;
860
+ while (i < text.length) {
861
+ const ansi = extractAnsiCode(text, i);
862
+ if (ansi) {
863
+ pendingAnsi += ansi.code;
864
+ i += ansi.length;
865
+ continue;
866
+ }
867
+
868
+ if (text[i] === "\t") {
869
+ if (keepContiguousPrefix && keptWidth + 3 <= targetWidth) {
870
+ if (pendingAnsi) {
871
+ result += pendingAnsi;
872
+ pendingAnsi = "";
873
+ }
874
+ result += "\t";
875
+ keptWidth += 3;
876
+ } else {
877
+ keepContiguousPrefix = false;
878
+ pendingAnsi = "";
879
+ }
880
+ visibleSoFar += 3;
881
+ if (visibleSoFar > maxWidth) {
882
+ overflowed = true;
883
+ break;
884
+ }
885
+ i++;
886
+ continue;
887
+ }
888
+
889
+ let end = i;
890
+ while (end < text.length && text[end] !== "\t") {
891
+ const nextAnsi = extractAnsiCode(text, end);
892
+ if (nextAnsi) {
893
+ break;
894
+ }
895
+ end++;
896
+ }
897
+
898
+ for (const { segment } of segmenter.segment(text.slice(i, end))) {
899
+ const width = graphemeWidth(segment);
900
+ if (keepContiguousPrefix && keptWidth + width <= targetWidth) {
901
+ if (pendingAnsi) {
902
+ result += pendingAnsi;
903
+ pendingAnsi = "";
904
+ }
905
+ result += segment;
906
+ keptWidth += width;
907
+ } else {
908
+ keepContiguousPrefix = false;
909
+ pendingAnsi = "";
910
+ }
911
+
912
+ visibleSoFar += width;
913
+ if (visibleSoFar > maxWidth) {
914
+ overflowed = true;
915
+ break;
916
+ }
917
+ }
918
+ if (overflowed) {
919
+ break;
920
+ }
921
+ i = end;
922
+ }
923
+ exhaustedInput = i >= text.length;
924
+ }
925
+
926
+ if (!overflowed && exhaustedInput) {
927
+ return pad ? text + " ".repeat(Math.max(0, maxWidth - visibleSoFar)) : text;
928
+ }
929
+
930
+ return finalizeTruncatedResult(result, keptWidth, ellipsis, ellipsisWidth, maxWidth, pad);
931
+ }
932
+
933
+ /**
934
+ * Extract a range of visible columns from a line. Handles ANSI codes and wide chars.
935
+ * @param strict - If true, exclude wide chars at boundary that would extend past the range
936
+ */
937
+ export function sliceByColumn(line: string, startCol: number, length: number, strict = false): string {
938
+ return sliceWithWidth(line, startCol, length, strict).text;
939
+ }
940
+
941
+ /** Like sliceByColumn but also returns the actual visible width of the result. */
942
+ export function sliceWithWidth(
943
+ line: string,
944
+ startCol: number,
945
+ length: number,
946
+ strict = false,
947
+ ): { text: string; width: number } {
948
+ if (length <= 0) return { text: "", width: 0 };
949
+ const endCol = startCol + length;
950
+ let result = "",
951
+ resultWidth = 0,
952
+ currentCol = 0,
953
+ i = 0,
954
+ pendingAnsi = "";
955
+
956
+ while (i < line.length) {
957
+ const ansi = extractAnsiCode(line, i);
958
+ if (ansi) {
959
+ if (currentCol >= startCol && currentCol < endCol) result += ansi.code;
960
+ else if (currentCol < startCol) pendingAnsi += ansi.code;
961
+ i += ansi.length;
962
+ continue;
963
+ }
964
+
965
+ let textEnd = i;
966
+ while (textEnd < line.length && !extractAnsiCode(line, textEnd)) textEnd++;
967
+
968
+ for (const { segment } of segmenter.segment(line.slice(i, textEnd))) {
969
+ const w = graphemeWidth(segment);
970
+ const inRange = currentCol >= startCol && currentCol < endCol;
971
+ const fits = !strict || currentCol + w <= endCol;
972
+ if (inRange && fits) {
973
+ if (pendingAnsi) {
974
+ result += pendingAnsi;
975
+ pendingAnsi = "";
976
+ }
977
+ result += segment;
978
+ resultWidth += w;
979
+ }
980
+ currentCol += w;
981
+ if (currentCol >= endCol) break;
982
+ }
983
+ i = textEnd;
984
+ if (currentCol >= endCol) break;
985
+ }
986
+ return { text: result, width: resultWidth };
987
+ }
988
+
989
+ // Pooled tracker instance for extractSegments (avoids allocation per call)
990
+ const pooledStyleTracker = new AnsiCodeTracker();
991
+
992
+ /**
993
+ * Extract "before" and "after" segments from a line in a single pass.
994
+ * Used for overlay compositing where we need content before and after the overlay region.
995
+ * Preserves styling from before the overlay that should affect content after it.
996
+ */
997
+ export function extractSegments(
998
+ line: string,
999
+ beforeEnd: number,
1000
+ afterStart: number,
1001
+ afterLen: number,
1002
+ strictAfter = false,
1003
+ ): { before: string; beforeWidth: number; after: string; afterWidth: number } {
1004
+ let before = "",
1005
+ beforeWidth = 0,
1006
+ after = "",
1007
+ afterWidth = 0;
1008
+ let currentCol = 0,
1009
+ i = 0;
1010
+ let pendingAnsiBefore = "";
1011
+ let afterStarted = false;
1012
+ const afterEnd = afterStart + afterLen;
1013
+
1014
+ // Track styling state so "after" inherits styling from before the overlay
1015
+ pooledStyleTracker.clear();
1016
+
1017
+ while (i < line.length) {
1018
+ const ansi = extractAnsiCode(line, i);
1019
+ if (ansi) {
1020
+ // Track all SGR codes to know styling state at afterStart
1021
+ pooledStyleTracker.process(ansi.code);
1022
+ // Include ANSI codes in their respective segments
1023
+ if (currentCol < beforeEnd) {
1024
+ pendingAnsiBefore += ansi.code;
1025
+ } else if (currentCol >= afterStart && currentCol < afterEnd && afterStarted) {
1026
+ // Only include after we've started "after" (styling already prepended)
1027
+ after += ansi.code;
1028
+ }
1029
+ i += ansi.length;
1030
+ continue;
1031
+ }
1032
+
1033
+ let textEnd = i;
1034
+ while (textEnd < line.length && !extractAnsiCode(line, textEnd)) textEnd++;
1035
+
1036
+ for (const { segment } of segmenter.segment(line.slice(i, textEnd))) {
1037
+ const w = graphemeWidth(segment);
1038
+
1039
+ if (currentCol < beforeEnd) {
1040
+ if (pendingAnsiBefore) {
1041
+ before += pendingAnsiBefore;
1042
+ pendingAnsiBefore = "";
1043
+ }
1044
+ before += segment;
1045
+ beforeWidth += w;
1046
+ } else if (currentCol >= afterStart && currentCol < afterEnd) {
1047
+ const fits = !strictAfter || currentCol + w <= afterEnd;
1048
+ if (fits) {
1049
+ // On first "after" grapheme, prepend inherited styling from before overlay
1050
+ if (!afterStarted) {
1051
+ after += pooledStyleTracker.getActiveCodes();
1052
+ afterStarted = true;
1053
+ }
1054
+ after += segment;
1055
+ afterWidth += w;
1056
+ }
1057
+ }
1058
+
1059
+ currentCol += w;
1060
+ // Early exit: done with "before" only, or done with both segments
1061
+ if (afterLen <= 0 ? currentCol >= beforeEnd : currentCol >= afterEnd) break;
1062
+ }
1063
+ i = textEnd;
1064
+ if (afterLen <= 0 ? currentCol >= beforeEnd : currentCol >= afterEnd) break;
1065
+ }
1066
+
1067
+ return { before, beforeWidth, after, afterWidth };
1068
+ }