@draht/tui 2026.3.2-2

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