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